How to use arg_to_path method in pytest-django

Best Python code snippet using pytest-django_python

arguments.py

Source:arguments.py Github

copy

Full Screen

1"""2Module providing a ConfigurationProvider backed by the program arguments3"""4import argparse5import sys6from typing import Any, Callable, Dict, List, Tuple, Type7from nectarine.configuration_provider import ConfigurationProvider, Path8from nectarine.dataclasses import get_paths9from nectarine.errors import NectarineStrictLoadingError10from nectarine.typing import is_primitive, is_tuple, is_linear_collection, is_parsable, is_literal, \11 get_generic_args12from nectarine._utils import insert_at_path, try_convert13class StoreTrueOrNone(argparse.Action):14 def __call__(self, parser, namespace, values, option_string=None):15 setattr(namespace, self.dest, True)16def _make_tuple_action(types: Tuple[Type]):17 class TupleAction(argparse.Action):18 def __init__(self, *args, **kwargs):19 super().__init__(*args, **kwargs)20 self.tuple_types = types21 def __call__(self, parser, namespace, values, option_string=None):22 assert len(values) == len(self.tuple_types)23 values = tuple(try_convert(v, t) for v, t in zip(values, self.tuple_types))24 setattr(namespace, self.dest, values)25 return TupleAction26def path_to_flag_name(path: Path) -> str:27 name = '-'.join(path).replace('_', '-')28 return name29def flag_name_to_path(flag_name: str) -> Path:30 flag_name = flag_name.lstrip('--')31 return tuple(flag_name.split('-'))32def _is_supported_type(type_: Type) -> bool:33 if is_primitive(type_):34 return True35 if is_linear_collection(type_):36 value_type = get_generic_args(type_)[0]37 return is_primitive(value_type) or is_parsable(value_type)38 if is_tuple(type_):39 values_types = get_generic_args(type_)40 return all(is_primitive(t) for t in values_types)41 if is_literal(type_):42 return is_primitive(type_)43 return False44def _add_argument_for(parser: argparse.ArgumentParser, name, field):45 kwargs = {"metavar": "[value]", "required": False}46 if field.type is bool:47 parser.add_argument(f"--{name}", action=StoreTrueOrNone, nargs=0, required=False)48 elif is_primitive(field.type):49 parser.add_argument(f"--{name}", type=lambda x: try_convert(x, field.type), **kwargs)50 elif is_linear_collection(field.type):51 value_type = get_generic_args(field.type)[0]52 if is_primitive(value_type):53 parser.add_argument(f"--{name}", action='append', type=lambda x: try_convert(x, value_type), **kwargs)54 else:55 assert is_parsable(value_type)56 parser.add_argument(f"--{name}", action='append', type=str, **kwargs)57 elif is_tuple(field.type): # This is matched only for fixed-length tuples58 values_types = get_generic_args(field.type)59 parser.add_argument(f"--{name}", nargs=len(values_types), action=_make_tuple_action(values_types), **kwargs)60 elif is_literal(field.type):61 allowed_values = get_generic_args(field.type)62 parser.add_argument(f"--{name}", choices=allowed_values, nargs='?')63def _argument_parser_for(64 target_type: Type,65 flag_name_converter: Callable[[Path], str] = None66):67 arg_to_path = {}68 flag_name_converter = flag_name_converter or path_to_flag_name69 parser = argparse.ArgumentParser(allow_abbrev=False, add_help=True)70 paths = ((path, field) for path, field in get_paths(target_type) if _is_supported_type(field.type))71 for path, field in paths:72 arg_name = flag_name_converter(path)73 arg_to_path[arg_name] = path74 _add_argument_for(parser, arg_name, field)75 return parser, arg_to_path76def argument_parser_for(77 target_type: Type,78 flag_name_converter: Callable[[Path], str] = None79) -> argparse.ArgumentParser:80 """81 Retrieve an argument parser82 :param target_type: the target type83 :param flag_name_converter: the function used to generate flag names from paths84 """85 return _argument_parser_for(target_type, flag_name_converter)[0]86class Arguments(ConfigurationProvider):87 def __init__(88 self,89 argv: List[str] = None,90 flag_name_converter: Callable[[Path], str] = None,91 ):92 self.argv = argv if argv is not None else sys.argv[1:]93 self.flag_name_converter = flag_name_converter or path_to_flag_name94 def load_configuration(self, target_type: Type, strict=False) -> Dict[str, Any]:95 parser, arg_to_path = _argument_parser_for(target_type, self.flag_name_converter)96 args, unknown = parser.parse_known_args(self.argv)97 if unknown:98 raise NectarineStrictLoadingError(offending_keys=[flag_name_to_path(f) for f in unknown])99 result = {}100 for arg_name, value in vars(args).items():101 if value is not None:102 insert_at_path(result, arg_to_path[arg_name.replace('_', '-')], value)103 return result104def arguments(105 argv: List[str] = None,106 flag_name_converter: Callable[[Path], str] = None,107):108 """109 Configure a provider that reads from the program arguments110 :param argv: the argument vector to parse from111 :param flag_name_converter: the function used to generate flag names from paths112 """113 return Arguments(114 argv=argv,115 flag_name_converter=flag_name_converter...

Full Screen

Full Screen

args.py

Source:args.py Github

copy

Full Screen

1"""2Provider suitable to load configuration from program arguments3"""4import argparse5import sys6from typing import Any, Dict, List, Type7from pydantic.errors import ExtraError8from ._dict_utils import get_paths, insert_at_path9from ._types import Provider, Model10_TYPENAME_TO_TYPE = {11 "integer": int,12 "string": str,13 "number": float,14}15class _StoreTrueOrNone(argparse.Action):16 def __call__(self, parser, namespace, values, option_string=None):17 setattr(namespace, self.dest, True)18def _make_tuple_action(types):19 class TupleAction(argparse.Action):20 def __init__(self, *args, **kwargs):21 super().__init__(*args, **kwargs)22 self.tuple_types = types23 def __call__(self, parser, namespace, values, option_string=None):24 assert len(values) == len(self.tuple_types)25 values = tuple(_TYPENAME_TO_TYPE[t](v) for v, t in zip(values, self.tuple_types))26 setattr(namespace, self.dest, values)27 return TupleAction28def _path_to_flag_name(path) -> str:29 name = '-'.join(path).replace('_', '-')30 return name31def _flag_name_to_path(flag_name: str):32 flag_name = flag_name.lstrip('--')33 return tuple(flag_name.split('-'))34def _is_basic_type(type_: str) -> bool:35 return type_ in {"string", "integer", "number"}36def _is_supported_type(type_: str) -> bool:37 return type_ in {"string", "integer", "number", "boolean", "array"}38def _add_argument_for(parser: argparse.ArgumentParser, name, type_, schema):39 if type_ == "boolean":40 parser.add_argument(f"--{name}", action=_StoreTrueOrNone, nargs=0, required=False)41 elif _is_basic_type(type_):42 parser.add_argument(f"--{name}", type=_TYPENAME_TO_TYPE[type_], metavar="[value]", required=False)43 elif type_ == "array":44 items = schema["items"]45 if isinstance(items, dict):46 value_type = items["type"]47 if _is_basic_type(value_type):48 parser.add_argument(49 f"--{name}",50 action='append',51 type=_TYPENAME_TO_TYPE[value_type],52 metavar="[value]",53 required=False,54 )55 else:56 assert isinstance(items, list)57 items_types = [i["type"] for i in items]58 if all(_is_basic_type(t) for t in items_types):59 parser.add_argument(60 f"--{name}",61 nargs=len(items_types),62 action=_make_tuple_action(items_types),63 metavar="[value]",64 required=False,65 )66def _argument_parser_for(target: Type[Model]):67 arg_to_path = {}68 parser = argparse.ArgumentParser(allow_abbrev=False, add_help=True)69 paths = ((path, type_, sch) for path, type_, sch in get_paths(target) if _is_supported_type(type_))70 for path, type_, sch in paths:71 arg_name = _path_to_flag_name(path)72 arg_to_path[arg_name] = path73 _add_argument_for(parser, arg_name, type_, sch)74 return parser, arg_to_path75def argument_parser_for(target: Type[Model]) -> argparse.ArgumentParser:76 """77 Retrieve an argument parser suitable for a given type78 :param target: the target type79 """80 return _argument_parser_for(target)[0]81def args(82 argv: List[str] = None,83) -> Provider:84 """85 Configure a provider that reads from the program arguments86 :param argv: the argument vector to parse from87 """88 argv = argv if argv is not None else sys.argv[1:]89 def load_from_args(target: Type[Model]) -> Dict[str, Any]:90 parser, arg_to_path = _argument_parser_for(target)91 parsed, unknown = parser.parse_known_args(argv)92 if unknown:93 raise ExtraError94 result = {}95 for name, value in vars(parsed).items():96 if value is not None:97 insert_at_path(result, arg_to_path[name.replace("_", "-")], value)98 return result...

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 pytest-django 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