Best Python code snippet using yandex-tank
api_docs.py
Source:api_docs.py  
...393        self.view.request.method = method394        operation = super(AutoSchema, self).get_operation(path, method)395        operation.update(kwargs)396        return operation397    def _validate_examples(self, path, method, examples,398                           serializer_class=None, many=False,399                           example_key='resp'):400        #pylint:disable=too-many-arguments,too-many-locals401        view = self.view402        many = many or (method == 'GET' and hasattr(view, 'list'))403        if many:404            if view.pagination_class:405                class APISerializer(NoModelSerializer):406                    count = serializers.IntegerField(407                        help_text=_("Total number of items in the dataset"))408                    previous = serializers.CharField(409                        required=False, allow_null=True,410                        help_text=_("URL to previous page of results"))411                    next = serializers.CharField(412                        required=False, allow_null=True,413                        help_text=_("URL to next page of results"))414                    results = serializer_class(many=hasattr(view, 'list'),415                        help_text=_("items in current page"))416                serializer_class = APISerializer417        serializer = None418        if examples:419            for example in examples:420                path_parts = path.split('/')421                if not example['path']:422                    warnings.warn('%s example has no path (%s)' % (423                        path, example['path']))424                else:425                    query_idx = example['path'].find('?')426                    if query_idx >= 0:427                        example_path_parts = example['path'][:query_idx].split(428                            '/')429                    else:430                        example_path_parts = example['path'].split('/')431                    # XXX ending with {path} will always fail here.432                    #if len(example_path_parts) != len(path_parts):433                    #    warnings.warn('%s has different parts from %s' % (434                    #        example['path'], path))435                    for path_part, example_path_part in zip(436                            path_parts, example_path_parts):437                        if path_part.startswith('{'):438                            continue439                        if example_path_part != path_part:440                            warnings.warn(441                                '%s does not match pattern %s ("%s"!="%s")' % (442                                example['path'], path,443                                example_path_part, path_part))444                            break445                if example_key in example:446                    if serializer_class is not None:447                        try:448                            kwargs = {}449                            serializer = serializer_class(450                                data=example[example_key],451                                context=view.get_serializer_context(),452                                **kwargs)453                            serializer.is_valid(raise_exception=True)454                        except (exceptions.ValidationError, Http404) as err:455                            # is_valid will also run `UniqueValidator` which456                            # is not what we want here, especially457                            # on GET requests.458                            warnings.warn('%(view)s: %(method)s %(path)s'\459                                ' invalid example for %(example_key)s:'\460                                ' %(example)s, err=%(err)s' % {461                                    'view': view.__class__.__name__,462                                    'method': method,463                                    'path': path,464                                    'example_key': example_key,465                                    'example': example,466                                    'err': err})467                    else:468                        warnings.warn('%(view)s: %(method)s %(path)s'\469                            ' example present but no serializer for'\470                            ' %(example_key)s: %(example)s' % {471                                'view': view.__class__.__name__,472                                'method': method,473                                'path': path,474                                'example_key': example_key,475                                'example': example})476                elif serializer_class is not None:477                    warnings.warn('%(view)s: %(method)s %(path)s'\478                        ' has no %(example_key)s: %(example)s' % {479                            'view': view.__class__.__name__,480                            'method': method,481                            'path': path,482                            'example_key': example_key,483                            'example': example})484        else:485            warnings.warn('%(view)s: %(method)s %(path)s has no examples' % {486                    'view': view.__class__.__name__,487                    'method': method,488                    'path': path})489            serializer = serializer_class(context=view.get_serializer_context())490        return serializer491    def get_request_body(self, path, method):492        view = self.view493        if method not in ('PUT', 'PATCH', 'POST'):494            return {}495        serializer_class = None496        if not hasattr(view, 'request'):497            view.request = HttpRequest(DangoHttpRequest())498            view.request.method = method499        if hasattr(view, 'get_serializer_class'):500            serializer_class = view.get_serializer_class()501        view_method = getattr(self.view, method.lower(), None)502        if view_method and hasattr(view_method, '_swagger_auto_schema'):503            #pylint:disable=protected-access504            data = view_method._swagger_auto_schema505            request_body_serializer_class = data.get('request_body', None)506            if request_body_serializer_class is not None:507                serializer_class = request_body_serializer_class508                if not issubclass(serializer_class, serializers.Serializer):509                    # We assume `request_body=no_body` here.510                    serializer_class = None511        serializer = None512        try:513            if method.lower() != 'patch':514                # XXX We disable showing patch as they are so close515                # to put requests.516                serializer = self._validate_examples(path, method,517                    self.examples if hasattr(self, 'examples') else [],518                    serializer_class=serializer_class,519                    example_key='requestBody')520        except exceptions.APIException:521            serializer = None522            warnings.warn('{}: serializer_class() raised an exception during '523                          'schema generation. Serializer fields will not be '524                          'generated for {} {}.'525                          .format(view.__class__.__name__, method, path))526        if not isinstance(serializer, serializers.Serializer):527            return {}528        content = self.map_serializer(serializer)529        # No required fields for PATCH530        if method == 'PATCH':531            del content['required']532        # No read_only fields for request.533        for name, schema in content['properties'].copy().items():534            if 'readOnly' in schema:535                del content['properties'][name]536        return {537            'content': {538                ct: {'schema': content}539                for ct in self.get_request_media_types()540            }541        }542    def get_responses(self, path, method):543        # TODO: Handle multiple codes.544        content = {}545        view = self.view546        serializer = None547        if method in ('DELETE',):548            return {'204': {'description': "NO CONTENT"}}549        many = False550        serializer_class = None551        if not hasattr(view, 'request'):552            view.request = HttpRequest(DangoHttpRequest())553            view.request.method = method554        if hasattr(view, 'get_serializer_class'):555            serializer_class = view.get_serializer_class()556        view_method = getattr(self.view, method.lower(), None)557        if view_method and hasattr(view_method, '_swagger_auto_schema'):558            #pylint:disable=protected-access,unused-variable559            data = view_method._swagger_auto_schema560            for resp_code, resp in six.iteritems(data.get('responses', {})):561                request_body_serializer = resp.schema562                if request_body_serializer is not None:563                    serializer_class = request_body_serializer564                    try:565                        if not issubclass(566                                serializer_class, serializers.Serializer):567                            # We assume `request_body=no_body` here.568                            serializer_class = None569                    except TypeError:570                        # We are dealing with a ListSerializer instance571                        serializer_class = \572                            request_body_serializer.child.__class__573                        many = request_body_serializer.many574                break # XXX only handles first schema response.575        if serializer_class or hasattr(view, 'get_serializer_class'):576            try:577                serializer = self._validate_examples(path, method,578                    self.examples if hasattr(self, 'examples') else [],579                    serializer_class=serializer_class, many=many)580            except exceptions.APIException:581                serializer = None582                warnings.warn('{}: serializer_class() raised an exception'583                    ' during '584                    'schema generation. Serializer fields will not be '585                    'generated for {} {}.'.format(586                        view.__class__.__name__, method, path))587            if isinstance(serializer, serializers.Serializer):588                content = self.map_serializer(serializer)589                # No write_only fields for response.590                for name, schema in content['properties'].copy().items():591                    if 'writeOnly' in schema:...main.py
Source:main.py  
...240                raise UserWarning(241                    'Method errors must be a list of RpcError subclasses'242                )243    if examples is not None:244        _validate_examples(examples)245    if validators is not None:246        unknown = set(validators.keys()) - set(func.__code__.co_varnames)247        if unknown:248            raise UserWarning(249                "Found validator(s) for nonexistent argument(s): "250                ", ".join(unknown)251            )252def _validate_examples(examples: Any) -> None:253    if not isinstance(examples, list):254        raise UserWarning()255    struct: Dict[str, Optional[type]] = {256        'name': str,257        'description': str,258        'summary': str,259        'params': list,260        'result': None,261    }262    struct_keys = set(struct.keys())263    for ex in examples:264        if not isinstance(ex, dict):265            raise UserWarning266        ex_keys = set(ex.keys())...validate_examples.py
Source:validate_examples.py  
...30    if artifact_location:31        copytree(artifact_location, staging_dir, dirs_exist_ok=True)32    else:33        stage_client_files(staging_dir, True)34def _validate_examples(35    driver_glob_expression: str, ip_address: str, device_name: str, artifact_location: Optional[str]36) -> None:37    staging_dir = Path(__file__).parent.parent.parent / "build" / "validate_examples"38    staging_dir = staging_dir.resolve()39    print(f"Validating examples using staging_dir: {staging_dir}")40    with _create_stage_dir(staging_dir):41        _system("poetry new .")42        _system("poetry add grpcio")43        _system("poetry add --dev grpcio-tools mypy mypy-protobuf types-protobuf grpc-stubs")44        # black requires python >=3.6.2, so only ask it to be installed for python >=3.6.2, or else45        # poetry can give a SolverProblemError and fail the "install" step46        _system('poetry add --dev --python ">=3.6.2" black')47        _system("poetry install")48        _stage_client_files(artifact_location, staging_dir)49        examples_dir = staging_dir / "examples"50        proto_dir = staging_dir / "proto"51        proto_files_str = str.join(" ", [file.name for file in proto_dir.glob("*.proto")])52        _system(53            rf"poetry run python -m grpc_tools.protoc -I{proto_dir} --python_out=. --grpc_python_out=. --mypy_out=. --mypy_grpc_out=. {proto_files_str}"54        )55        for dir in examples_dir.glob(driver_glob_expression):56            print()57            print(f"-- Validating: {dir.name}")58            print(f" -> Running black line-length 100")59            _system(f"poetry run black --check --line-length 100 {dir}")60            print(f" -> Running mypy")61            _system(f"poetry run mypy {dir} --check-untyped-defs")62            if ip_address:63                for file in dir.glob("*.py"):64                    print(f" -> Running example: {file.name}")65                    port = 3176366                    _system(rf"poetry run python {file} {ip_address} {port} {device_name}")67if __name__ == "__main__":68    parser = ArgumentParser(description="Validate grpc-device examples.")69    parser.add_argument(70        "-p",71        "--pattern",72        help="Glob expression for scrapigen driver names to validate (i.e., *rfmx*).",73    )74    parser.add_argument(75        "-s",76        "--server",77        help="grpc-device server IP address. If not specified, skip running examples.",78    )79    parser.add_argument(80        "-d",81        "--device",82        help="Device alias to run examples. Default: no device passed to example (uses session-level simulation).",83        default="",84    )85    parser.add_argument(86        "-a",87        "--artifacts",88        help="Pre-existing client artifact directory. If set, these files will be used. Otherwise, artifacts will be staged from source.",89        default=None,90    )91    args = parser.parse_args()92    _validate_examples(args.pattern, args.server, args.device, args.artifacts)93    if any(_FAILED_COMMANDS):94        for code, command in _FAILED_COMMANDS:95            print(f"FAILED STEP ({code}): [{command}]")...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
