How to use read_keyval method in autotest

Best Python code snippet using autotest_python

parsing.py

Source:parsing.py Github

copy

Full Screen

...39 def read_comment(self, value):40 matches = self.comment_matcher(value)41 if matches:42 return matches.group('comment')43 def read_keyval(self, value):44 return read_keyval(value)45 def _read(self, contents):46 data = defaultdict(OrderedDict)47 section = None48 options = None49 option_name, option_value = None, None50 spaces = ' ' * self.tab_indent51 def clean(line):52 line = line.replace('\t', spaces)53 return line54 for i, line in enumerate(contents.splitlines(False)):55 line = clean(line)56 comment = self.comment_matcher(line)57 if comment:58 logger.debug('got comment', comment.group('comment'))59 continue60 elif not line:61 continue62 elif line.startswith('[') and line.strip().endswith(']'):63 section = line.strip()[1:-1]64 options = data[section]65 continue66 elif line and line[0] != ' ':67 # an option_name?68 n, v = self.read_keyval(line)69 if not n:70 break71 if n and v in ('', None):72 # an open option73 option_name = n74 option_value = WaitingValue(section, option_name)75 options[option_name] = option_value76 continue77 elif n and v:78 # a self clausing option79 option_name, option_value = n, v80 options[n] = InlinedValue(section, n, v)81 option_name, option_value = None, None82 continue83 raise ParsingError(repr(line), i, option_value)84 if isinstance(option_value, WaitingValue):85 # a waiting value!86 option_value = MultilineValue(section,87 option_name,88 line)89 options[option_name] = option_value90 continue91 elif isinstance(option_value, MultilineValue):92 # a multiline value93 option_value.value += '\n' + line94 continue95 else:96 raise ParsingError(repr(line), i, option_value)97 # and now resolve data98 response = defaultdict(OrderedDict)99 for section, options in data.items():100 opts = response[section]101 for name, value in options.items():102 opts[name] = value.resolve()103 return self._sections.update(response)104 def defaults(self):105 return dict(self._defaults)106 def has_option(self, section, option):107 """docstring for get"""108 try:109 self.get(section, option)110 except NoOptionError:111 return False112 return True113 def has_section(self, section):114 for provider in (self._user, self._sections, self._defaults):115 if section in provider:116 return True117 return False118 def sections(self):119 """docstring for sections"""120 merged = set()121 for provider in (self._user, self._sections, self._defaults):122 merged.update(provider.keys())123 return sorted(merged)124 def options(self, section):125 merged = set()126 defined = False127 for provider in (self._user, self._sections, self._defaults):128 try:129 merged.update(provider[section].keys())130 defined = True131 except KeyError:132 pass133 if not defined:134 raise NoSectionError('section {} is not defined'.format(section))135 return sorted(merged)136 def items(self, section):137 merged = dict()138 defined = False139 for provider in (self._defaults, self._sections, self._user):140 try:141 merged.update(provider[section])142 defined = True143 except KeyError:144 pass145 if not defined:146 raise NoSectionError('section {} is not defined'.format(section))147 return merged.items()148 def get(self, section, option):149 """150 Get an option value for the named section.151 """152 for provider in (self._user, self._sections, self._defaults):153 try:154 return provider[section][option]155 except KeyError:156 pass157 raise NoOptionError(option, section)158 def getint(self, section, option):159 """160 A convenience method which coerces the option in the specified section161 to an integer.162 """163 return int(self.get(section, option))164 def getfloat(self, section, option):165 """166 A convenience method which coerces the option in the specified section167 to a floating point number.168 """169 return float(self.get(section, option))170 def getboolean(self, section, option):171 """172 A convenience method which coerces the option in the specified section173 to a floating point number.174 """175 value = self.get(section, option)176 if str(value).lower() in ('1', 'yes', 'true', "on"):177 return True178 if str(value).lower() in ('0', 'no', 'false', 'off'):179 return False180 raise ValueError('cannot use it as a boolean value')181 def getmulti(self, section, option, nested=False):182 """183 A convenience method which coerces the option in the specified section184 to a list value.185 for example, this configuration file::186 [section]187 foo =188 bar189 baz190 will be parsed has::191 assert parser.getmulti('section', 'foo') == ['bar', 'baz']192 """193 data = self.get(section, option)194 if '\n' not in data and self.read_keyval(data)[0] is None:195 # oneliner version196 return data.strip().split()197 # block version198 if not nested:199 return [element for element in data.strip().split('\n')]200 def walk(data):201 """docstring for walk"""202 response = []203 option_name = None204 option_value = None205 for element in data.split('\n'):206 if element and element.startswith(' '):207 option_value.append(element)208 continue209 if option_name:210 response.append({option_name: walk(dedent('\n'.join(option_value)))})211 option_name = None212 option_value = None213 n, v = self.read_keyval(element)214 if not n:215 response.append(element)216 option_name = None217 option_value = None218 continue219 elif v:220 response.append({n: v})221 option_name = None222 option_value = None223 continue224 option_name = n225 option_value = []226 if option_name:227 response.append({option_name: walk(dedent('\n'.join(option_value)))})228 return response229 return walk(data)230 def getfile(self, section, option):231 """232 A convenience method which loads the content of option.233 """234 with open(self.get(section, option), 'r') as file:235 return file.read()236 def getcsv(self, section, option):237 """238 A convenience method which coerces the option in the specified section239 to a list value.240 for example, this configuration file::241 [section]242 foo = bar, baz quux243 quux = bar baz244 will be parsed has::245 assert parser.getcsv('section', 'foo') == ['bar', 'baz quux']246 assert parser.getcsv('section', 'quux') == ['bar', 'baz']247 """248 elements = self.get(section, option)249 splitter = ',' if ',' in elements else None250 return [element.strip() for element in elements.split(splitter)]251class InlinedValue(object):252 def __init__(self, section, key, value):253 self.section = section254 self.key = key255 self.value = value256 def resolve(self):257 return self.value258class MultilineValue(object):259 def __init__(self, section, key, value):260 self.section = section261 self.key = key262 self.value = value263 def resolve(self):264 value = dedent(self.value)265 if value and value.startswith(' '):266 msg = 'Mixed indentations levels in {}:{}:\n{!r}'267 raise ValueError(msg.format(self.section, self.key, value))268 return value269 def __str__(self):270 return '{}'.format(self.value)271 def __repr__(self):272 return '{!r}'.format(self.value)273class WaitingValue(object):274 def __init__(self, section, key):275 self.section = section276 self.key = key277 def resolve(self):278 return None279keyval_matcher = re.compile("""280 ^(?P<key>.+?)281 \s*282 (?<![<>=!])=283 \s*284 (?P<value>.+?)?285 \s*$286""", re.X).match287def read_keyval(data):288 """docstring for read_keyval"""289 matches = keyval_matcher(data)290 if not matches:291 return None, None292 else:...

Full Screen

Full Screen

regression.py

Source:regression.py Github

copy

Full Screen

...8 Compare two (old, new) keyvalue files9 compare_list: list of tuples ('field_name', 'regression_op')10 regression_op(a,b) return 0 if not regression, and ~0 otherwise11 """12 kv_old = utils.read_keyval(old)13 kv_new = utils.read_keyval(new)14 failed = 015 first_regression = None16 logging.info('========= Comparison table for %30s =========' % self.tagged_testname)17 logging.info("%20s | %10s | %10s | %10s | %10s | %s" % ('field name', 'old value', 'new value', 'cmp res', 'status', 'cmp function'))18 for field, cmpfn in compare_list:19 if not field in kv_old:20 raise error.TestError('Cant not find field:%s in %s' % (field, old + '/keyval'))21 if not field in kv_new:22 raise error.TestError('Cant not find field:%s in %s' % (field, new + '/keyval'))23 res = cmpfn(kv_old[field], kv_new[field])24 if res:25 failed += 126 msg = 'FAIL'27 if not first_regression:...

Full Screen

Full Screen

test_parsing.py

Source:test_parsing.py Github

copy

Full Screen

...25 ' pattern2',26 ' pattern3'27 ]28 def test_keyval(self):29 assert read_keyval('foo') == (None, None)30 assert read_keyval('foo = bar') == ('foo', 'bar')31 assert read_keyval('foo = ') == ('foo', None)32 assert read_keyval('foo >= bar = baz') == ('foo >= bar', 'baz')33 assert read_keyval('foo = bar >= baz') == ('foo', 'bar >= baz')...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful