How to use _parse_list method in localstack

Best Python code snippet using localstack_python

config.py

Source:config.py Github

copy

Full Screen

...177 else:178 setter(value)179 self.set_options.append(option_name)180 @classmethod181 def _parse_list(cls, value, separator=','):182 """Represents value as a list.183 Value is split either by separator (defaults to comma) or by lines.184 :param value:185 :param separator: List items separator character.186 :rtype: list187 """188 if isinstance(value, list): # _get_parser_compound case189 return value190 if '\n' in value:191 value = value.splitlines()192 else:193 value = value.split(separator)194 return [chunk.strip() for chunk in value if chunk.strip()]195 @classmethod196 def _parse_dict(cls, value):197 """Represents value as a dict.198 :param value:199 :rtype: dict200 """201 separator = '='202 result = {}203 for line in cls._parse_list(value):204 key, sep, val = line.partition(separator)205 if sep != separator:206 raise DistutilsOptionError(207 'Unable to parse option value to dict: %s' % value)208 result[key.strip()] = val.strip()209 return result210 @classmethod211 def _parse_bool(cls, value):212 """Represents value as boolean.213 :param value:214 :rtype: bool215 """216 value = value.lower()217 return value in ('1', 'true', 'yes')218 @classmethod219 def _exclude_files_parser(cls, key):220 """Returns a parser function to make sure field inputs221 are not files.222 Parses a value after getting the key so error messages are223 more informative.224 :param key:225 :rtype: callable226 """227 def parser(value):228 exclude_directive = 'file:'229 if value.startswith(exclude_directive):230 raise ValueError(231 'Only strings are accepted for the {0} field, '232 'files are not accepted'.format(key))233 return value234 return parser235 @classmethod236 def _parse_file(cls, value):237 """Represents value as a string, allowing including text238 from nearest files using `file:` directive.239 Directive is sandboxed and won't reach anything outside240 directory with setup.py.241 Examples:242 file: README.rst, CHANGELOG.md, src/file.txt243 :param str value:244 :rtype: str245 """246 include_directive = 'file:'247 if not isinstance(value, str):248 return value249 if not value.startswith(include_directive):250 return value251 spec = value[len(include_directive):]252 filepaths = (os.path.abspath(path.strip()) for path in spec.split(','))253 return '\n'.join(254 cls._read_file(path)255 for path in filepaths256 if (cls._assert_local(path) or True)257 and os.path.isfile(path)258 )259 @staticmethod260 def _assert_local(filepath):261 if not filepath.startswith(os.getcwd()):262 raise DistutilsOptionError(263 '`file:` directive can not access %s' % filepath)264 @staticmethod265 def _read_file(filepath):266 with io.open(filepath, encoding='utf-8') as f:267 return f.read()268 @classmethod269 def _parse_attr(cls, value, package_dir=None):270 """Represents value as a module attribute.271 Examples:272 attr: package.attr273 attr: package.module.attr274 :param str value:275 :rtype: str276 """277 attr_directive = 'attr:'278 if not value.startswith(attr_directive):279 return value280 attrs_path = value.replace(attr_directive, '').strip().split('.')281 attr_name = attrs_path.pop()282 module_name = '.'.join(attrs_path)283 module_name = module_name or '__init__'284 parent_path = os.getcwd()285 if package_dir:286 if attrs_path[0] in package_dir:287 # A custom path was specified for the module we want to import288 custom_path = package_dir[attrs_path[0]]289 parts = custom_path.rsplit('/', 1)290 if len(parts) > 1:291 parent_path = os.path.join(os.getcwd(), parts[0])292 module_name = parts[1]293 else:294 module_name = custom_path295 elif '' in package_dir:296 # A custom parent directory was specified for all root modules297 parent_path = os.path.join(os.getcwd(), package_dir[''])298 with patch_path(parent_path):299 try:300 # attempt to load value statically301 return getattr(StaticModule(module_name), attr_name)302 except Exception:303 # fallback to simple import304 module = importlib.import_module(module_name)305 return getattr(module, attr_name)306 @classmethod307 def _get_parser_compound(cls, *parse_methods):308 """Returns parser function to represents value as a list.309 Parses a value applying given methods one after another.310 :param parse_methods:311 :rtype: callable312 """313 def parse(value):314 parsed = value315 for method in parse_methods:316 parsed = method(parsed)317 return parsed318 return parse319 @classmethod320 def _parse_section_to_dict(cls, section_options, values_parser=None):321 """Parses section options into a dictionary.322 Optionally applies a given parser to values.323 :param dict section_options:324 :param callable values_parser:325 :rtype: dict326 """327 value = {}328 values_parser = values_parser or (lambda val: val)329 for key, (_, val) in section_options.items():330 value[key] = values_parser(val)331 return value332 def parse_section(self, section_options):333 """Parses configuration file section.334 :param dict section_options:335 """336 for (name, (_, value)) in section_options.items():337 try:338 self[name] = value339 except KeyError:340 pass # Keep silent for a new option may appear anytime.341 def parse(self):342 """Parses configuration file items from one343 or more related sections.344 """345 for section_name, section_options in self.sections.items():346 method_postfix = ''347 if section_name: # [section.option] variant348 method_postfix = '_%s' % section_name349 section_parser_method = getattr(350 self,351 # Dots in section names are translated into dunderscores.352 ('parse_section%s' % method_postfix).replace('.', '__'),353 None)354 if section_parser_method is None:355 raise DistutilsOptionError(356 'Unsupported distribution option section: [%s.%s]' % (357 self.section_prefix, section_name))358 section_parser_method(section_options)359 def _deprecated_config_handler(self, func, msg, warning_class):360 """ this function will wrap around parameters that are deprecated361 :param msg: deprecation message362 :param warning_class: class of warning exception to be raised363 :param func: function to be wrapped around364 """365 @wraps(func)366 def config_handler(*args, **kwargs):367 warnings.warn(msg, warning_class)368 return func(*args, **kwargs)369 return config_handler370class ConfigMetadataHandler(ConfigHandler):371 section_prefix = 'metadata'372 aliases = {373 'home_page': 'url',374 'summary': 'description',375 'classifier': 'classifiers',376 'platform': 'platforms',377 }378 strict_mode = False379 """We need to keep it loose, to be partially compatible with380 `pbr` and `d2to1` packages which also uses `metadata` section.381 """382 def __init__(self, target_obj, options, ignore_option_errors=False,383 package_dir=None):384 super(ConfigMetadataHandler, self).__init__(target_obj, options,385 ignore_option_errors)386 self.package_dir = package_dir387 @property388 def parsers(self):389 """Metadata item name to parser function mapping."""390 parse_list = self._parse_list391 parse_file = self._parse_file392 parse_dict = self._parse_dict393 exclude_files_parser = self._exclude_files_parser394 return {395 'platforms': parse_list,396 'keywords': parse_list,397 'provides': parse_list,398 'requires': self._deprecated_config_handler(399 parse_list,400 "The requires parameter is deprecated, please use "401 "install_requires for runtime dependencies.",402 DeprecationWarning),403 'obsoletes': parse_list,404 'classifiers': self._get_parser_compound(parse_file, parse_list),405 'license': exclude_files_parser('license'),406 'license_files': parse_list,407 'description': parse_file,408 'long_description': parse_file,409 'version': self._parse_version,410 'project_urls': parse_dict,411 }412 def _parse_version(self, value):413 """Parses `version` option value.414 :param value:415 :rtype: str416 """417 version = self._parse_file(value)418 if version != value:419 version = version.strip()420 # Be strict about versions loaded from file because it's easy to421 # accidentally include newlines and other unintended content422 if isinstance(parse(version), LegacyVersion):423 tmpl = (424 'Version loaded from {value} does not '425 'comply with PEP 440: {version}'426 )427 raise DistutilsOptionError(tmpl.format(**locals()))428 return version429 version = self._parse_attr(value, self.package_dir)430 if callable(version):431 version = version()432 if not isinstance(version, str):433 if hasattr(version, '__iter__'):434 version = '.'.join(map(str, version))435 else:436 version = '%s' % version437 return version438class ConfigOptionsHandler(ConfigHandler):439 section_prefix = 'options'440 @property441 def parsers(self):442 """Metadata item name to parser function mapping."""443 parse_list = self._parse_list444 parse_list_semicolon = partial(self._parse_list, separator=';')445 parse_bool = self._parse_bool446 parse_dict = self._parse_dict447 parse_cmdclass = self._parse_cmdclass448 return {449 'zip_safe': parse_bool,450 'use_2to3': parse_bool,451 'include_package_data': parse_bool,452 'package_dir': parse_dict,453 'use_2to3_fixers': parse_list,454 'use_2to3_exclude_fixers': parse_list,455 'convert_2to3_doctests': parse_list,456 'scripts': parse_list,457 'eager_resources': parse_list,458 'dependency_links': parse_list,459 'namespace_packages': parse_list,460 'install_requires': parse_list_semicolon,461 'setup_requires': parse_list_semicolon,462 'tests_require': parse_list_semicolon,463 'packages': self._parse_packages,464 'entry_points': self._parse_file,465 'py_modules': parse_list,466 'python_requires': SpecifierSet,467 'cmdclass': parse_cmdclass,468 }469 def _parse_cmdclass(self, value):470 def resolve_class(qualified_class_name):471 idx = qualified_class_name.rfind('.')472 class_name = qualified_class_name[idx+1:]473 pkg_name = qualified_class_name[:idx]474 module = __import__(pkg_name)475 return getattr(module, class_name)476 return {477 k: resolve_class(v)478 for k, v in self._parse_dict(value).items()479 }480 def _parse_packages(self, value):481 """Parses `packages` option value.482 :param value:483 :rtype: list484 """485 find_directives = ['find:', 'find_namespace:']486 trimmed_value = value.strip()487 if trimmed_value not in find_directives:488 return self._parse_list(value)489 findns = trimmed_value == find_directives[1]490 # Read function arguments from a dedicated section.491 find_kwargs = self.parse_section_packages__find(492 self.sections.get('packages.find', {}))493 if findns:494 from setuptools import find_namespace_packages as find_packages495 else:496 from setuptools import find_packages497 return find_packages(**find_kwargs)498 def parse_section_packages__find(self, section_options):499 """Parses `packages.find` configuration file section.500 To be used in conjunction with _parse_packages().501 :param dict section_options:502 """...

Full Screen

Full Screen

parse.py

Source:parse.py Github

copy

Full Screen

...46 def _parse_none(self, obj, depth=0):47 """ Always return None; Handy for eliminating objects we don't want48 results for. """49 return None50 def _parse_list(self, obj, depth=0):51 """ Recursivly parses lists, then returns the parsed de-duped results. """52 ret = []53 for item in obj:54 ret.append(self._parser(item, depth=depth))55 try:56 return list(set(ret))57 except TypeError:58 return ret59 def _parse_simple(self, obj, depth=0):60 """ Return the object sent to us, no further parsing needed """61 return obj62 def _parse_name(self, obj, depth=0):63 """ returns the object as a string. Often a simple way to convert to64 human readable form """...

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 localstack 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