diff --git a/.chronus/changes/require_black_all-2024-4-6-14-29-30.md b/.chronus/changes/require_black_all-2024-4-6-14-29-30.md new file mode 100644 index 00000000000..76dc6cc4eae --- /dev/null +++ b/.chronus/changes/require_black_all-2024-4-6-14-29-30.md @@ -0,0 +1,8 @@ +--- +changeKind: internal +packages: + - "@autorest/python" + - "@azure-tools/typespec-python" +--- + +run black on whole repo \ No newline at end of file diff --git a/eng/pipelines/ci-template.yml b/eng/pipelines/ci-template.yml index b25ad4ae2b6..ce609e390f1 100644 --- a/eng/pipelines/ci-template.yml +++ b/eng/pipelines/ci-template.yml @@ -94,7 +94,7 @@ steps: workingDirectory: $(Build.SourcesDirectory)/autorest.python/packages/${{parameters.folderName}} condition: and(succeeded(), ${{ parameters.pythonCodeChecks }}) - - script: black ${{parameters.pythonFolderName}} + - script: black $(Build.SourcesDirectory)/autorest.python displayName: Black workingDirectory: $(Build.SourcesDirectory)/autorest.python/packages/${{parameters.folderName}} condition: and(succeeded(), ${{ parameters.pythonCodeChecks }}) diff --git a/eng/scripts/build.py b/eng/scripts/build.py index 8b31ab5b566..1c621423722 100644 --- a/eng/scripts/build.py +++ b/eng/scripts/build.py @@ -14,6 +14,7 @@ pipeline_build = is_pipeline_build() root_dir = Path.resolve(Path(__file__) / "../../..") + def main(package_name: str, version_suffix: str, output_dir: str, package_versions: dict): if package_name == "autorest.python": versionVariableName = "generatorVersion" @@ -46,9 +47,7 @@ def main(package_name: str, version_suffix: str, output_dir: str, package_versio if pipeline_build: # Update version variable - print( - f"##vso[task.setvariable variable={versionVariableName};isOutput=true]{newVersion}" - ) + print(f"##vso[task.setvariable variable={versionVariableName};isOutput=true]{newVersion}") # Build project call("pnpm run build") @@ -133,15 +132,17 @@ def main(package_name: str, version_suffix: str, output_dir: str, package_versio if "autorest.python" in package_versions: version = package_versions["autorest.python"] if args.publish_internal: - overrides["@autorest/python"] = f'{feedUrl}/@autorest/python/-/python-{version}.tgz' + overrides["@autorest/python"] = f"{feedUrl}/@autorest/python/-/python-{version}.tgz" if "typespec-python" in package_versions: version = package_versions["typespec-python"] if args.publish_internal: - overrides["@azure-tools/typespec-python"] = f'{feedUrl}/@azure-tools/typespec-python/-/typespec-python-{version}.tgz' - + overrides["@azure-tools/typespec-python"] = ( + f"{feedUrl}/@azure-tools/typespec-python/-/typespec-python-{version}.tgz" + ) + with open(output_dir / "overrides.json", "w") as fp: - json.dump(overrides, fp, indent=2) + json.dump(overrides, fp, indent=2) with open(output_dir / "package-versions.json", "w") as fp: json.dump(package_versions, fp, indent=2) diff --git a/eng/scripts/helpers.py b/eng/scripts/helpers.py index 16e11b679d3..4046c51c586 100644 --- a/eng/scripts/helpers.py +++ b/eng/scripts/helpers.py @@ -24,10 +24,12 @@ def str2bool(v): else: raise argparse.ArgumentTypeError("Boolean value expected.") + def is_pipeline_build(): return not not os.environ.get("TF_BUILD", "") -def call(cmd:str, cwd=root_dir, suppress_failures=False, capture_output=False): + +def call(cmd: str, cwd=root_dir, suppress_failures=False, capture_output=False): print("\n============================================================") print(f"From {cwd}\n> {cmd}") print("============================================================", flush=True) @@ -45,13 +47,13 @@ def call(cmd:str, cwd=root_dir, suppress_failures=False, capture_output=False): returncode = process.returncode - if(capture_output): + if capture_output: print(process.stdout.rstrip(), flush=True) elapsed_time = time.time() - start_time command_failed = returncode != 0 and not suppress_failures - + print("------------------------------------------------------------") if command_failed: print(f"##[error]Command failed: {cmd}") diff --git a/eng/scripts/run_apiview.py b/eng/scripts/run_apiview.py index b79ddf253ed..7b47a65b6d6 100644 --- a/eng/scripts/run_apiview.py +++ b/eng/scripts/run_apiview.py @@ -27,14 +27,8 @@ def _single_dir_apiview(mod): ] ) except CalledProcessError as e: - if ( - loop >= 2 - ): # retry for maximum 3 times because sometimes the apistubgen has transient failure. - logging.error( - "{} exited with apiview generation error {}".format( - mod.stem, e.returncode - ) - ) + if loop >= 2: # retry for maximum 3 times because sometimes the apistubgen has transient failure. + logging.error("{} exited with apiview generation error {}".format(mod.stem, e.returncode)) return False else: loop += 1 diff --git a/eng/scripts/run_mypy.py b/eng/scripts/run_mypy.py index 125791c1340..0ee18401849 100644 --- a/eng/scripts/run_mypy.py +++ b/eng/scripts/run_mypy.py @@ -20,9 +20,7 @@ def _single_dir_mypy(mod): - inner_class = next( - d for d in mod.iterdir() if d.is_dir() and not str(d).endswith("egg-info") - ) + inner_class = next(d for d in mod.iterdir() if d.is_dir() and not str(d).endswith("egg-info")) try: check_call( [ @@ -37,9 +35,7 @@ def _single_dir_mypy(mod): ) return True except CalledProcessError as e: - logging.error( - "{} exited with mypy error {}".format(inner_class.stem, e.returncode) - ) + logging.error("{} exited with mypy error {}".format(inner_class.stem, e.returncode)) return False diff --git a/eng/scripts/run_pylint.py b/eng/scripts/run_pylint.py index 0ade909f481..9c72240b9ba 100644 --- a/eng/scripts/run_pylint.py +++ b/eng/scripts/run_pylint.py @@ -20,9 +20,7 @@ def _single_dir_pylint(mod): - inner_class = next( - d for d in mod.iterdir() if d.is_dir() and not str(d).endswith("egg-info") - ) + inner_class = next(d for d in mod.iterdir() if d.is_dir() and not str(d).endswith("egg-info")) try: check_call( [ @@ -37,9 +35,7 @@ def _single_dir_pylint(mod): ) return True except CalledProcessError as e: - logging.error( - "{} exited with linting error {}".format(inner_class.stem, e.returncode) - ) + logging.error("{} exited with linting error {}".format(inner_class.stem, e.returncode)) return False diff --git a/eng/scripts/run_pyright.py b/eng/scripts/run_pyright.py index ed65d4f04e5..decfb9c80e5 100644 --- a/eng/scripts/run_pyright.py +++ b/eng/scripts/run_pyright.py @@ -18,9 +18,7 @@ def _single_dir_pyright(mod): - inner_class = next( - d for d in mod.iterdir() if d.is_dir() and not str(d).endswith("egg-info") - ) + inner_class = next(d for d in mod.iterdir() if d.is_dir() and not str(d).endswith("egg-info")) retries = 3 while retries: try: @@ -37,9 +35,7 @@ def _single_dir_pyright(mod): ) return True except CalledProcessError as e: - logging.exception( - "{} exited with pyright error {}".format(inner_class.stem, e.returncode) - ) + logging.exception("{} exited with pyright error {}".format(inner_class.stem, e.returncode)) logging.error(f"PyRight stdout:\n{e.stdout}\n===========") logging.error(f"PyRight stderr:\n{e.stderr}\n===========") # PyRight has shown to randomly failed with a 217, retry the same folder 3 times should help diff --git a/eng/scripts/test.py b/eng/scripts/test.py index 83e96cc126f..ab6aa149485 100644 --- a/eng/scripts/test.py +++ b/eng/scripts/test.py @@ -13,9 +13,7 @@ root_dir = Path.resolve(Path(__file__) / "../../..") -def main( - package_name: str, regenerate: bool, check_change: bool, check_code: bool = False -): +def main(package_name: str, regenerate: bool, check_change: bool, check_code: bool = False): if package_name == "autorest.python": folder_name = "autorest" elif package_name == "typespec-python": @@ -49,7 +47,7 @@ def main( # Pyright call(f"pyright {folder_name}", cwd=package_dir) # Black - call(f"black {folder_name}", cwd=package_dir) + call(f"black .", cwd=package_dir) # Fail on black autorest diff call("node ./eng/scripts/check-for-changed-files.js") # Unit tests diff --git a/eng/scripts/util.py b/eng/scripts/util.py index 86c762ed1bb..0df185ab76e 100644 --- a/eng/scripts/util.py +++ b/eng/scripts/util.py @@ -62,21 +62,12 @@ def run_check(name, call_back, log_info): args = parser.parse_args() - pkg_dir = ( - Path(ROOT_FOLDER) - / Path(f"packages/{args.package}") - / Path("test") - / Path(args.test_folder) - ) + pkg_dir = Path(ROOT_FOLDER) / Path(f"packages/{args.package}") / Path("test") / Path(args.test_folder) if args.generator: pkg_dir /= Path(args.generator) if args.subfolder: pkg_dir /= Path(args.subfolder) - dirs = [ - d - for d in pkg_dir.iterdir() - if d.is_dir() and not d.stem.startswith("_") and d.stem not in IGNORE_FOLDER - ] + dirs = [d for d in pkg_dir.iterdir() if d.is_dir() and not d.stem.startswith("_") and d.stem not in IGNORE_FOLDER] if args.file_name: dirs = [d for d in dirs if d.stem.lower() == args.file_name.lower()] if len(dirs) > 1: diff --git a/packages/autorest.python/autorest/__init__.py b/packages/autorest.python/autorest/__init__.py index 70d90391373..1fa6e0b83c8 100644 --- a/packages/autorest.python/autorest/__init__.py +++ b/packages/autorest.python/autorest/__init__.py @@ -34,9 +34,7 @@ def __init__(self, *, output_folder: Union[str, Path], **kwargs: Any) -> None: python_json = {} self.options = kwargs if python_json: - _LOGGER.warning( - "Loading python.json file. This behavior will be depreacted" - ) + _LOGGER.warning("Loading python.json file. This behavior will be depreacted") self.options.update(python_json) def read_file(self, path: Union[str, Path]) -> str: @@ -61,9 +59,7 @@ def list_file(self) -> List[str]: class ReaderAndWriterAutorest(ReaderAndWriter): - def __init__( - self, *, output_folder: Union[str, Path], autorestapi: AutorestAPI - ) -> None: + def __init__(self, *, output_folder: Union[str, Path], autorestapi: AutorestAPI) -> None: super().__init__(output_folder=output_folder) self._autorestapi = autorestapi @@ -97,9 +93,7 @@ def process(self) -> bool: class PluginAutorest(Plugin, ReaderAndWriterAutorest): """For our Autorest plugins, we want to take autorest api as input as options, then pass it to the Plugin""" - def __init__( - self, autorestapi: AutorestAPI, *, output_folder: Union[str, Path] - ) -> None: + def __init__(self, autorestapi: AutorestAPI, *, output_folder: Union[str, Path]) -> None: super().__init__(autorestapi=autorestapi, output_folder=output_folder) self.options = self.get_options() @@ -141,9 +135,7 @@ def update_yaml(self, yaml_data: Dict[str, Any]) -> None: raise NotImplementedError() -class YamlUpdatePluginAutorest( # pylint: disable=abstract-method - YamlUpdatePlugin, PluginAutorest -): +class YamlUpdatePluginAutorest(YamlUpdatePlugin, PluginAutorest): # pylint: disable=abstract-method def get_yaml(self) -> Dict[str, Any]: return yaml.safe_load(self.read_file("code-model-v4-no-tags.yaml")) diff --git a/packages/autorest.python/autorest/_utils.py b/packages/autorest.python/autorest/_utils.py index 8282a34c21f..95bf493bde8 100644 --- a/packages/autorest.python/autorest/_utils.py +++ b/packages/autorest.python/autorest/_utils.py @@ -8,9 +8,7 @@ import argparse -def update_enum_value( - name: str, value: Any, description: str, enum_type: Dict[str, Any] -) -> Dict[str, Any]: +def update_enum_value(name: str, value: Any, description: str, enum_type: Dict[str, Any]) -> Dict[str, Any]: return { "name": name, "type": "enumvalue", @@ -37,12 +35,7 @@ def replace_upper_characters(m) -> str: and len(name) - next_non_upper_case_char_location > 1 and name[next_non_upper_case_char_location].isalpha() ): - return ( - prefix - + match_str[: len(match_str) - 1] - + "_" - + match_str[len(match_str) - 1] - ) + return prefix + match_str[: len(match_str) - 1] + "_" + match_str[len(match_str) - 1] return prefix + match_str @@ -89,12 +82,8 @@ def _get_value(value: Any) -> Any: return value unknown_args_ret = { - ua.strip("--").split("=", maxsplit=1)[ # pylint: disable=bad-str-strip-call - 0 - ]: _get_value( - ua.strip("--").split("=", maxsplit=1)[ # pylint: disable=bad-str-strip-call - 1 - ] + ua.strip("--").split("=", maxsplit=1)[0]: _get_value( # pylint: disable=bad-str-strip-call + ua.strip("--").split("=", maxsplit=1)[1] # pylint: disable=bad-str-strip-call ) for ua in unknown_args } @@ -136,11 +125,7 @@ def build_policies( "self._config.user_agent_policy", "self._config.proxy_policy", "policies.ContentDecodePolicy(**kwargs)", - ( - f"{async_prefix}ARMAutoResourceProviderRegistrationPolicy()" - if is_arm - else None - ), + (f"{async_prefix}ARMAutoResourceProviderRegistrationPolicy()" if is_arm else None), "self._config.redirect_policy", "self._config.retry_policy", "self._config.authentication_policy", diff --git a/packages/autorest.python/autorest/black/__init__.py b/packages/autorest.python/autorest/black/__init__.py index 37f4ae5cb7b..8df1c79241c 100644 --- a/packages/autorest.python/autorest/black/__init__.py +++ b/packages/autorest.python/autorest/black/__init__.py @@ -55,9 +55,7 @@ def process(self) -> bool: def format_file(self, file: Path) -> None: try: file_content = self.read_file(file) - file_content = black.format_file_contents( - file_content, fast=True, mode=_BLACK_MODE - ) + file_content = black.format_file_contents(file_content, fast=True, mode=_BLACK_MODE) except NothingChanged: pass except: # pylint: disable=bare-except diff --git a/packages/autorest.python/autorest/codegen/__init__.py b/packages/autorest.python/autorest/codegen/__init__.py index 027fe5cdb6e..ecfb70f5752 100644 --- a/packages/autorest.python/autorest/codegen/__init__.py +++ b/packages/autorest.python/autorest/codegen/__init__.py @@ -55,25 +55,18 @@ def __getattr__(self, prop: str) -> Any: @property def company_name(self) -> str: - return self.options.get( - "company-name", "Microsoft" if self.is_azure_flavor else "" - ) + return self.options.get("company-name", "Microsoft" if self.is_azure_flavor else "") @property def license_header(self) -> str: license_header = self.options.get( "header-text", - ( - DEFAULT_HEADER_TEXT.format(company_name=self.company_name) - if self.company_name - else "" - ), + (DEFAULT_HEADER_TEXT.format(company_name=self.company_name) if self.company_name else ""), ) if license_header: license_header = license_header.replace("\n", "\n# ") license_header = ( - "# --------------------------------------------------------------------------\n# " - + license_header + "# --------------------------------------------------------------------------\n# " + license_header ) license_header += "\n# --------------------------------------------------------------------------" return license_header @@ -84,9 +77,7 @@ def show_operations(self) -> bool: @property def _models_mode_default(self) -> str: - models_mode_default = ( - "none" if self.low_level_client or self.version_tolerant else "msrest" - ) + models_mode_default = "none" if self.low_level_client or self.version_tolerant else "msrest" if self.options.get("cadl_file") is not None: models_mode_default = "dpg" return models_mode_default @@ -98,9 +89,7 @@ def original_models_mode(self) -> str: @property def models_mode(self) -> Union[str, bool]: # switch to falsy value for easier code writing - return ( - False if self.original_models_mode == "none" else self.original_models_mode - ) + return False if self.original_models_mode == "none" else self.original_models_mode @property def tracing(self) -> bool: @@ -136,9 +125,7 @@ def combine_operation_files(self) -> bool: @property def package_pprint_name(self) -> str: - return self.options.get("package-pprint-name") or _default_pprint( - str(self.package_name) - ) + return self.options.get("package-pprint-name") or _default_pprint(str(self.package_name)) @property def default_optional_constants_to_none(self) -> bool: @@ -162,9 +149,7 @@ def head_as_boolean(self) -> bool: @property def package_mode(self) -> str: - return self.options.get("packaging-files-dir") or self.options.get( - "package-mode", "" - ) + return self.options.get("packaging-files-dir") or self.options.get("package-mode", "") @property def packaging_files_config(self) -> Optional[Dict[str, Any]]: @@ -175,10 +160,7 @@ def packaging_files_config(self) -> Optional[Dict[str, Any]]: # if it's a string, we can split on the comma to get the dict # otherwise we just return try: - return { - k.strip(): v.strip() - for k, v in [i.split(":") for i in packaging_files_config.split("|")] - } + return {k.strip(): v.strip() for k, v in [i.split(":") for i in packaging_files_config.split("|")]} except AttributeError: return packaging_files_config @@ -194,10 +176,7 @@ def _validate_code_model_options(self) -> None: "hidden", "embedded", ]: - raise ValueError( - "The value of --builders-visibility must be either 'public', 'hidden', " - "or 'embedded'" - ) + raise ValueError("The value of --builders-visibility must be either 'public', 'hidden', or 'embedded'") if self.options_retriever.original_models_mode not in ["msrest", "dpg", "none"]: raise ValueError( @@ -206,32 +185,20 @@ def _validate_code_model_options(self) -> None: "'none' if you don't want any." ) - if ( - not self.options_retriever.show_operations - and self.options_retriever.builders_visibility == "embedded" - ): + if not self.options_retriever.show_operations and self.options_retriever.builders_visibility == "embedded": raise ValueError( "Can not embed builders without operations. " "Either set --show-operations to True, or change the value of --builders-visibility " "to 'public' or 'hidden'." ) - if ( - self.options_retriever.basic_setup_py - and not self.options_retriever.package_version - ): + if self.options_retriever.basic_setup_py and not self.options_retriever.package_version: raise ValueError("--basic-setup-py must be used with --package-version") - if ( - self.options_retriever.package_mode - and not self.options_retriever.package_version - ): + if self.options_retriever.package_mode and not self.options_retriever.package_version: raise ValueError("--package-mode must be used with --package-version") - if ( - not self.options_retriever.show_operations - and self.options_retriever.combine_operation_files - ): + if not self.options_retriever.show_operations and self.options_retriever.combine_operation_files: raise ValueError( "Can not combine operation files if you are not showing operations. " "If you want operation files, pass in flag --show-operations" @@ -258,26 +225,16 @@ def _validate_code_model_options(self) -> None: "We are working on creating a new multiapi SDK for version tolerant and it is not available yet." ) - if ( - self.options_retriever.client_side_validation - and self.options_retriever.version_tolerant - ): - raise ValueError( - "Can not generate version tolerant with --client-side-validation. " - ) + if self.options_retriever.client_side_validation and self.options_retriever.version_tolerant: + raise ValueError("Can not generate version tolerant with --client-side-validation. ") - if not ( - self.options_retriever.azure_arm or self.options_retriever.version_tolerant - ): + if not (self.options_retriever.azure_arm or self.options_retriever.version_tolerant): _LOGGER.warning( "You are generating with options that would not allow the SDK to be shipped as an official Azure SDK. " "Please read https://aka.ms/azsdk/dpcodegen for more details." ) - if ( - not self.options_retriever.is_azure_flavor - and self.options_retriever.tracing - ): + if not self.options_retriever.is_azure_flavor and self.options_retriever.tracing: raise ValueError("Can only have tracing turned on for Azure SDKs.") @staticmethod @@ -292,8 +249,7 @@ def remove_cloud_errors(yaml_data: Dict[str, Any]) -> None: exception = operation["exceptions"][i] if ( exception.get("schema") - and exception["schema"]["language"]["default"]["name"] - == "CloudError" + and exception["schema"]["language"]["default"]["name"] == "CloudError" ): del operation["exceptions"][i] i -= 1 @@ -360,9 +316,7 @@ def process(self) -> bool: self.remove_cloud_errors(yaml_data) code_model = CodeModel(yaml_data=yaml_data, options=options) - if not self.options_retriever.is_azure_flavor and any( - client.lro_operations for client in code_model.clients - ): + if not self.options_retriever.is_azure_flavor and any(client.lro_operations for client in code_model.clients): raise ValueError("Only support LROs for Azure SDKs") serializer = self.get_serializer(code_model) serializer.serialize() @@ -373,10 +327,7 @@ def process(self) -> bool: class CodeGeneratorAutorest(CodeGenerator, PluginAutorest): def get_options(self) -> Dict[str, Any]: if self._autorestapi.get_boolean_value("python3-only") is False: - _LOGGER.warning( - "You have passed in --python3-only=False. We have force overriden " - "this to True." - ) + _LOGGER.warning("You have passed in --python3-only=False. We have force overriden this to True.") if self._autorestapi.get_boolean_value("add-python3-operation-files"): _LOGGER.warning( "You have passed in --add-python3-operation-files. " @@ -391,49 +342,31 @@ def get_options(self) -> Dict[str, Any]: options = { "azure-arm": self._autorestapi.get_boolean_value("azure-arm"), "header-text": self._autorestapi.get_value("header-text"), - "low-level-client": self._autorestapi.get_boolean_value( - "low-level-client", False - ), - "version-tolerant": self._autorestapi.get_boolean_value( - "version-tolerant", True - ), + "low-level-client": self._autorestapi.get_boolean_value("low-level-client", False), + "version-tolerant": self._autorestapi.get_boolean_value("version-tolerant", True), "show-operations": self._autorestapi.get_boolean_value("show-operations"), "python3-only": self._autorestapi.get_boolean_value("python3-only"), - "head-as-boolean": self._autorestapi.get_boolean_value( - "head-as-boolean", False - ), - "keep-version-file": self._autorestapi.get_boolean_value( - "keep-version-file" - ), + "head-as-boolean": self._autorestapi.get_boolean_value("head-as-boolean", False), + "keep-version-file": self._autorestapi.get_boolean_value("keep-version-file"), "no-async": self._autorestapi.get_boolean_value("no-async"), - "no-namespace-folders": self._autorestapi.get_boolean_value( - "no-namespace-folders" - ), + "no-namespace-folders": self._autorestapi.get_boolean_value("no-namespace-folders"), "basic-setup-py": self._autorestapi.get_boolean_value("basic-setup-py"), "package-name": self._autorestapi.get_value("package-name"), "package-version": self._autorestapi.get_value("package-version"), - "client-side-validation": self._autorestapi.get_boolean_value( - "client-side-validation" - ), + "client-side-validation": self._autorestapi.get_boolean_value("client-side-validation"), "tracing": self._autorestapi.get_boolean_value("trace"), "multiapi": self._autorestapi.get_boolean_value("multiapi", False), "polymorphic-examples": self._autorestapi.get_value("polymorphic-examples"), "models-mode": self._autorestapi.get_value("models-mode"), "builders-visibility": self._autorestapi.get_value("builders-visibility"), - "show-send-request": self._autorestapi.get_boolean_value( - "show-send-request" - ), + "show-send-request": self._autorestapi.get_boolean_value("show-send-request"), "only-path-and-body-params-positional": self._autorestapi.get_boolean_value( "only-path-and-body-params-positional" ), - "combine-operation-files": self._autorestapi.get_boolean_value( - "combine-operation-files" - ), + "combine-operation-files": self._autorestapi.get_boolean_value("combine-operation-files"), "package-mode": self._autorestapi.get_value("package-mode"), "package-pprint-name": self._autorestapi.get_value("package-pprint-name"), - "packaging-files-config": self._autorestapi.get_value( - "package-configuration" - ), + "packaging-files-config": self._autorestapi.get_value("package-configuration"), "default-optional-constants-to-none": self._autorestapi.get_boolean_value( "default-optional-constants-to-none" ), diff --git a/packages/autorest.python/autorest/codegen/models/__init__.py b/packages/autorest.python/autorest/codegen/models/__init__.py index 32854f31c89..7f9a8e0507c 100644 --- a/packages/autorest.python/autorest/codegen/models/__init__.py +++ b/packages/autorest.python/autorest/codegen/models/__init__.py @@ -198,7 +198,5 @@ def build_type(yaml_data: Dict[str, Any], code_model: CodeModel) -> BaseType: RequestBuilderType = Union[RequestBuilder, OverloadedRequestBuilder] -ParameterType = Union[ - Parameter, RequestBuilderParameter, ClientParameter, ConfigParameter -] +ParameterType = Union[Parameter, RequestBuilderParameter, ClientParameter, ConfigParameter] OperationType = Union[Operation, LROOperation, PagingOperation, LROPagingOperation] diff --git a/packages/autorest.python/autorest/codegen/models/base.py b/packages/autorest.python/autorest/codegen/models/base.py index a7e1c1a398f..7a44fb0b283 100644 --- a/packages/autorest.python/autorest/codegen/models/base.py +++ b/packages/autorest.python/autorest/codegen/models/base.py @@ -42,14 +42,10 @@ class BaseType(BaseModel, ABC): # pylint: disable=too-many-public-methods def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None: super().__init__(yaml_data, code_model) self.type = yaml_data["type"] # the type discriminator - self.api_versions: List[str] = yaml_data.get( - "apiVersions", [] - ) # api versions this type is in. + self.api_versions: List[str] = yaml_data.get("apiVersions", []) # api versions this type is in. @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "BaseType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "BaseType": return cls(yaml_data=yaml_data, code_model=code_model) def imports(self, **kwargs) -> FileImport: # pylint: disable=unused-argument diff --git a/packages/autorest.python/autorest/codegen/models/base_builder.py b/packages/autorest.python/autorest/codegen/models/base_builder.py index aaff4e2bae5..7bd5b2f4279 100644 --- a/packages/autorest.python/autorest/codegen/models/base_builder.py +++ b/packages/autorest.python/autorest/codegen/models/base_builder.py @@ -39,9 +39,7 @@ from .request_builder import RequestBuilder -OverloadListType = TypeVar( - "OverloadListType", bound=Union[List["Operation"], List["RequestBuilder"]] -) +OverloadListType = TypeVar("OverloadListType", bound=Union[List["Operation"], List["RequestBuilder"]]) _LOGGER = logging.getLogger(__name__) @@ -69,9 +67,7 @@ def __init__( self.overloads = overloads or cast(OverloadListType, []) self._summary: str = yaml_data.get("summary", "") self.want_tracing: bool = yaml_data.get("wantTracing", True) - self.group_name: str = yaml_data[ - "groupName" - ] # either operationGroup or client I am on + self.group_name: str = yaml_data["groupName"] # either operationGroup or client I am on self.is_overload: bool = yaml_data["isOverload"] self.api_versions: List[str] = yaml_data["apiVersions"] self.added_on: Optional[str] = yaml_data.get("addedOn") diff --git a/packages/autorest.python/autorest/codegen/models/client.py b/packages/autorest.python/autorest/codegen/models/client.py index 9945fab9ced..3d880e32852 100644 --- a/packages/autorest.python/autorest/codegen/models/client.py +++ b/packages/autorest.python/autorest/codegen/models/client.py @@ -40,9 +40,7 @@ def __init__( ): super().__init__(yaml_data, code_model) self.parameters = parameters - self.url: str = self.yaml_data[ - "url" - ] # the base endpoint of the client. Can be parameterized or not + self.url: str = self.yaml_data["url"] # the base endpoint of the client. Can be parameterized or not self.legacy_filename: str = self.yaml_data.get("legacyFilename", "client") @property @@ -139,11 +137,7 @@ def credential(self) -> Optional[Parameter]: @property def send_request_name(self) -> str: """Name of the send request function""" - return ( - "send_request" - if self.code_model.options["show_send_request"] - else "_send_request" - ) + return "send_request" if self.code_model.options["show_send_request"] else "_send_request" @property def has_parameterized_host(self) -> bool: @@ -170,48 +164,28 @@ def url_pylint_disable(self) -> str: @property def filename(self) -> str: """Name of the file for the client""" - if ( - self.code_model.options["version_tolerant"] - or self.code_model.options["low_level_client"] - ): + if self.code_model.options["version_tolerant"] or self.code_model.options["low_level_client"]: return "_client" return f"_{self.legacy_filename}" - def lookup_request_builder( - self, request_builder_id: int - ) -> Union[RequestBuilder, OverloadedRequestBuilder]: + def lookup_request_builder(self, request_builder_id: int) -> Union[RequestBuilder, OverloadedRequestBuilder]: """Find the request builder based off of id""" try: - return next( - rb - for rb in self.request_builders - if id(rb.yaml_data) == request_builder_id - ) + return next(rb for rb in self.request_builders if id(rb.yaml_data) == request_builder_id) except StopIteration as exc: - raise KeyError( - f"No request builder with id {request_builder_id} found." - ) from exc + raise KeyError(f"No request builder with id {request_builder_id} found.") from exc def lookup_operation(self, operation_id: int) -> "OperationType": try: - return next( - o - for og in self.operation_groups - for o in og.operations - if id(o.yaml_data) == operation_id - ) + return next(o for og in self.operation_groups for o in og.operations if id(o.yaml_data) == operation_id) except StopIteration as exc: raise KeyError(f"No operation with id {operation_id} found.") from exc def _imports_shared(self, async_mode: bool) -> FileImport: file_import = FileImport(self.code_model) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) if self.code_model.options["azure_arm"]: - file_import.add_submodule_import( - "azure.mgmt.core", self.pipeline_class(async_mode), ImportType.SDKCORE - ) + file_import.add_submodule_import("azure.mgmt.core", self.pipeline_class(async_mode), ImportType.SDKCORE) else: file_import.add_submodule_import( "" if self.code_model.is_azure_flavor else "runtime", @@ -261,11 +235,7 @@ def has_mixin(self) -> bool: @property def lro_operations(self) -> List["OperationType"]: """all LRO operations in this SDK?""" - return [ - operation - for operation_group in self.operation_groups - for operation in operation_group.lro_operations - ] + return [operation for operation_group in self.operation_groups for operation in operation_group.lro_operations] @property def has_public_lro_operations(self) -> bool: @@ -274,18 +244,14 @@ def has_public_lro_operations(self) -> bool: @property def has_operations(self) -> bool: - return any( - operation_group.has_operations for operation_group in self.operation_groups - ) + return any(operation_group.has_operations for operation_group in self.operation_groups) def link_lro_initial_operations(self) -> None: """Link each LRO operation to its initial operation""" for operation_group in self.operation_groups: for operation in operation_group.operations: if isinstance(operation, (LROOperation, LROPagingOperation)): - operation.initial_operation = self.lookup_operation( - id(operation.yaml_data["initialOperation"]) - ) + operation.initial_operation = self.lookup_operation(id(operation.yaml_data["initialOperation"])) @property def need_request_converter(self) -> bool: @@ -339,14 +305,9 @@ def imports(self, async_mode: bool) -> FileImport: ImportType.LOCAL, ) - if ( - self.code_model.model_types - and self.code_model.options["models_mode"] == "msrest" - ): + if self.code_model.model_types and self.code_model.options["models_mode"] == "msrest": path_to_models = ".." if async_mode else "." - file_import.add_submodule_import( - path_to_models, "models", ImportType.LOCAL, alias="_models" - ) + file_import.add_submodule_import(path_to_models, "models", ImportType.LOCAL, alias="_models") elif self.code_model.options["models_mode"] == "msrest": # in this case, we have client_models = {} in the service client, which needs a type annotation # this import will always be commented, so will always add it to the typing section @@ -356,22 +317,14 @@ def imports(self, async_mode: bool) -> FileImport: def imports_for_multiapi(self, async_mode: bool) -> FileImport: file_import = self._imports_shared(async_mode) - file_import.add_submodule_import( - "typing", "Optional", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Optional", ImportType.STDLIB, TypingSection.CONDITIONAL) try: mixin_operation = next(og for og in self.operation_groups if og.is_mixin) - file_import.add_submodule_import( - "._operations_mixin", mixin_operation.class_name, ImportType.LOCAL - ) + file_import.add_submodule_import("._operations_mixin", mixin_operation.class_name, ImportType.LOCAL) except StopIteration: pass - file_import.add_submodule_import( - "azure.profiles", "KnownProfiles", import_type=ImportType.SDKCORE - ) - file_import.add_submodule_import( - "azure.profiles", "ProfileDefinition", import_type=ImportType.SDKCORE - ) + file_import.add_submodule_import("azure.profiles", "KnownProfiles", import_type=ImportType.SDKCORE) + file_import.add_submodule_import("azure.profiles", "ProfileDefinition", import_type=ImportType.SDKCORE) file_import.add_submodule_import( "azure.profiles.multiapiclient", "MultiApiClientMixin", @@ -430,35 +383,20 @@ def _imports_shared(self, async_mode: bool) -> FileImport: "policies", ImportType.SDKCORE, ) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) if self.code_model.options["package_version"]: - file_import.add_submodule_import( - ".._version" if async_mode else "._version", "VERSION", ImportType.LOCAL - ) + file_import.add_submodule_import(".._version" if async_mode else "._version", "VERSION", ImportType.LOCAL) if self.code_model.options["azure_arm"]: - policy = ( - "AsyncARMChallengeAuthenticationPolicy" - if async_mode - else "ARMChallengeAuthenticationPolicy" - ) - file_import.add_submodule_import( - "azure.mgmt.core.policies", "ARMHttpLoggingPolicy", ImportType.SDKCORE - ) - file_import.add_submodule_import( - "azure.mgmt.core.policies", policy, ImportType.SDKCORE - ) + policy = "AsyncARMChallengeAuthenticationPolicy" if async_mode else "ARMChallengeAuthenticationPolicy" + file_import.add_submodule_import("azure.mgmt.core.policies", "ARMHttpLoggingPolicy", ImportType.SDKCORE) + file_import.add_submodule_import("azure.mgmt.core.policies", policy, ImportType.SDKCORE) return file_import def imports(self, async_mode: bool) -> FileImport: file_import = self._imports_shared(async_mode) for gp in self.parameters: - if ( - gp.method_location == ParameterMethodLocation.KWARG - and gp not in self.parameters.kwargs_to_pop - ): + if gp.method_location == ParameterMethodLocation.KWARG and gp not in self.parameters.kwargs_to_pop: continue file_import.merge( gp.imports( diff --git a/packages/autorest.python/autorest/codegen/models/code_model.py b/packages/autorest.python/autorest/codegen/models/code_model.py index 4c6a9ccfa96..ab3c41f4ac6 100644 --- a/packages/autorest.python/autorest/codegen/models/code_model.py +++ b/packages/autorest.python/autorest/codegen/models/code_model.py @@ -57,17 +57,11 @@ def __init__( for type_yaml in yaml_data.get("types", []): build_type(yaml_data=type_yaml, code_model=self) self.clients: List[Client] = [ - Client.from_yaml(client_yaml_data, self) - for client_yaml_data in yaml_data["clients"] + Client.from_yaml(client_yaml_data, self) for client_yaml_data in yaml_data["clients"] ] self.subnamespace_to_clients: Dict[str, List[Client]] = { - subnamespace: [ - Client.from_yaml(client_yaml, self, is_subclient=True) - for client_yaml in client_yamls - ] - for subnamespace, client_yamls in yaml_data.get( - "subnamespaceToClients", {} - ).items() + subnamespace: [Client.from_yaml(client_yaml, self, is_subclient=True) for client_yaml in client_yamls] + for subnamespace, client_yamls in yaml_data.get("subnamespaceToClients", {}).items() } if self.options["models_mode"] and self.model_types: self.sort_model_types() @@ -80,11 +74,7 @@ def __init__( @property def has_form_data(self) -> bool: - return any( - og.has_form_data_body - for client in self.clients - for og in client.operation_groups - ) + return any(og.has_form_data_body for client in self.clients for og in client.operation_groups) @property def has_etag(self) -> bool: @@ -94,25 +84,15 @@ def has_etag(self) -> bool: def has_operations(self) -> bool: if any(c for c in self.clients if c.has_operations): return True - return any( - c - for clients in self.subnamespace_to_clients.values() - for c in clients - if c.has_operations - ) + return any(c for clients in self.subnamespace_to_clients.values() for c in clients if c.has_operations) @property def has_non_abstract_operations(self) -> bool: return any(c for c in self.clients if c.has_non_abstract_operations) or any( - c - for cs in self.subnamespace_to_clients.values() - for c in cs - if c.has_non_abstract_operations + c for cs in self.subnamespace_to_clients.values() for c in cs if c.has_non_abstract_operations ) - def lookup_request_builder( - self, request_builder_id: int - ) -> Union[RequestBuilder, OverloadedRequestBuilder]: + def lookup_request_builder(self, request_builder_id: int) -> Union[RequestBuilder, OverloadedRequestBuilder]: """Find the request builder based off of id""" for client in self.clients: try: @@ -140,12 +120,7 @@ def need_vendored_code(self, async_mode: bool) -> bool: return True if async_mode: return self.need_mixin_abc - return ( - self.need_request_converter - or self.need_mixin_abc - or self.has_etag - or self.has_form_data - ) + return self.need_request_converter or self.need_mixin_abc or self.has_etag or self.has_form_data @property def need_request_converter(self) -> bool: @@ -164,10 +139,7 @@ def operations_folder_name(self) -> str: """Get the name of the operations folder that holds operations.""" name = "operations" if self.options["version_tolerant"] and not any( - og - for client in self.clients - for og in client.operation_groups - if not og.is_mixin + og for client in self.clients for og in client.operation_groups if not og.is_mixin ): name = f"_{name}" return name @@ -196,8 +168,7 @@ def model_types(self) -> List[ModelType]: self._model_types = [ t for t in self.types_map.values() - if isinstance(t, ModelType) - and not (self.options["models_mode"] == "dpg" and t.page_result_model) + if isinstance(t, ModelType) and not (self.options["models_mode"] == "dpg" and t.page_result_model) ] return self._model_types @@ -227,9 +198,7 @@ def _sort_model_types_helper( if current.id in seen_schema_yaml_ids: return [] if current.name in seen_schema_names: - raise ValueError( - f"We have already generated a schema with name {current.name}" - ) + raise ValueError(f"We have already generated a schema with name {current.name}") ancestors = [current] if current.parents: for parent in current.parents: @@ -237,12 +206,7 @@ def _sort_model_types_helper( continue seen_schema_names.add(current.name) seen_schema_yaml_ids.add(current.id) - ancestors = ( - self._sort_model_types_helper( - parent, seen_schema_names, seen_schema_yaml_ids - ) - + ancestors - ) + ancestors = self._sort_model_types_helper(parent, seen_schema_names, seen_schema_yaml_ids) + ancestors seen_schema_names.add(current.name) seen_schema_yaml_ids.add(current.id) return ancestors @@ -257,11 +221,7 @@ def sort_model_types(self) -> None: seen_schema_yaml_ids: Set[int] = set() sorted_object_schemas: List[ModelType] = [] for schema in sorted(self.model_types, key=lambda x: x.name.lower()): - sorted_object_schemas.extend( - self._sort_model_types_helper( - schema, seen_schema_names, seen_schema_yaml_ids - ) - ) + sorted_object_schemas.extend(self._sort_model_types_helper(schema, seen_schema_names, seen_schema_yaml_ids)) self.model_types = sorted_object_schemas @property diff --git a/packages/autorest.python/autorest/codegen/models/combined_type.py b/packages/autorest.python/autorest/codegen/models/combined_type.py index 57fafbce20e..a865a69c863 100644 --- a/packages/autorest.python/autorest/codegen/models/combined_type.py +++ b/packages/autorest.python/autorest/codegen/models/combined_type.py @@ -51,9 +51,7 @@ def serialization_type(self) -> str: def client_default_value(self) -> Any: return self.yaml_data.get("clientDefaultValue") - def description( - self, *, is_operation_file: bool # pylint: disable=unused-argument - ) -> str: + def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument if len(self.types) == 2: return f"Is either a {self.types[0].type_description} type or a {self.types[1].type_description} type." return f"Is one of the following types: {', '.join([t.type_description for t in self.types])}" @@ -75,9 +73,7 @@ def type_definition(self, **kwargs: Any) -> str: Special case for enum, for instance: Union[str, "EnumName"] """ # remove duplicates - inside_types = list( - dict.fromkeys([type.type_annotation(**kwargs) for type in self.types]) - ) + inside_types = list(dict.fromkeys([type.type_annotation(**kwargs) for type in self.types])) if len(inside_types) == 1: return inside_types[0] if self._is_union_of_literals: @@ -135,9 +131,7 @@ def imports(self, **kwargs: Any) -> FileImport: return file_import @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "BaseType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "BaseType": from . import build_type return cls( diff --git a/packages/autorest.python/autorest/codegen/models/constant_type.py b/packages/autorest.python/autorest/codegen/models/constant_type.py index 3a8f11933f6..16be177de4c 100644 --- a/packages/autorest.python/autorest/codegen/models/constant_type.py +++ b/packages/autorest.python/autorest/codegen/models/constant_type.py @@ -76,22 +76,14 @@ def docstring_type(self, **kwargs: Any) -> str: return self.value_type.docstring_type(**kwargs) def type_annotation(self, **kwargs: Any) -> str: - return ( - f"Literal[{self.get_declaration()}]" - if self._is_literal - else self.value_type.type_annotation(**kwargs) - ) + return f"Literal[{self.get_declaration()}]" if self._is_literal else self.value_type.type_annotation(**kwargs) @property def _is_literal(self) -> bool: - return isinstance( - self.value_type, (IntegerType, BinaryType, StringType, BooleanType) - ) + return isinstance(self.value_type, (IntegerType, BinaryType, StringType, BooleanType)) @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "ConstantType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "ConstantType": """Constructs a ConstantType from yaml data. :param yaml_data: the yaml data from which we will construct this schema @@ -134,9 +126,7 @@ def imports_for_multiapi(self, **kwargs: Any) -> FileImport: def imports(self, **kwargs: Any) -> FileImport: file_import = self._imports_shared(**kwargs) if self._is_literal: - file_import.add_submodule_import( - "typing", "Literal", ImportType.STDLIB, TypingSection.REGULAR - ) + file_import.add_submodule_import("typing", "Literal", ImportType.STDLIB, TypingSection.REGULAR) return file_import @property diff --git a/packages/autorest.python/autorest/codegen/models/credential_types.py b/packages/autorest.python/autorest/codegen/models/credential_types.py index 257791ce7f3..261cad0e228 100644 --- a/packages/autorest.python/autorest/codegen/models/credential_types.py +++ b/packages/autorest.python/autorest/codegen/models/credential_types.py @@ -57,9 +57,7 @@ def call(self, async_mode: bool) -> str: return f"policies.{policy_name}(self.credential, *self.credential_scopes, **kwargs)" @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "BearerTokenCredentialPolicyType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "BearerTokenCredentialPolicyType": return cls(yaml_data, code_model, yaml_data["credentialScopes"]) @@ -85,27 +83,17 @@ def __init__( @property def credential_name(self) -> str: - return ( - "AzureKeyCredential" - if self.code_model.is_azure_flavor - else "ServiceKeyCredential" - ) + return "AzureKeyCredential" if self.code_model.is_azure_flavor else "ServiceKeyCredential" def call(self, async_mode: bool) -> str: params = f'"{self.key}", ' if self.scheme: params += f'prefix="{self.scheme}", ' - return ( - f"policies.{self.credential_name}Policy(self.credential, {params}**kwargs)" - ) + return f"policies.{self.credential_name}Policy(self.credential, {params}**kwargs)" @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "KeyCredentialPolicyType": - return cls( - yaml_data, code_model, yaml_data["key"], yaml_data.get("scheme", None) - ) + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "KeyCredentialPolicyType": + return cls(yaml_data, code_model, yaml_data["key"], yaml_data.get("scheme", None)) CredentialPolicyType = TypeVar( @@ -118,9 +106,7 @@ def from_yaml( ) -class CredentialType( - Generic[CredentialPolicyType], BaseType -): # pylint:disable=abstract-method +class CredentialType(Generic[CredentialPolicyType], BaseType): # pylint:disable=abstract-method """Store info about the type of the credential. Can be either an KeyCredential or a TokenCredential""" def __init__( @@ -132,9 +118,7 @@ def __init__( super().__init__(yaml_data, code_model) self.policy = policy - def description( - self, *, is_operation_file: bool # pylint: disable=unused-argument - ) -> str: + def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument return "" def get_json_template_representation( @@ -144,9 +128,7 @@ def get_json_template_representation( client_default_value_declaration: Optional[str] = None, description: Optional[str] = None, ) -> Any: - raise TypeError( - "You should not try to get a JSON template representation of a CredentialSchema" - ) + raise TypeError("You should not try to get a JSON template representation of a CredentialSchema") def docstring_text(self, **kwargs: Any) -> str: return "credential" @@ -156,17 +138,13 @@ def serialization_type(self) -> str: return self.docstring_type() @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "CredentialType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "CredentialType": from . import build_type return cls( yaml_data, code_model, - policy=cast( - CredentialPolicyType, build_type(yaml_data["policy"], code_model) - ), + policy=cast(CredentialPolicyType, build_type(yaml_data["policy"], code_model)), ) @@ -225,9 +203,7 @@ class KeyCredentialType( """Type for an KeyCredential""" def docstring_type(self, **kwargs: Any) -> str: # pylint: disable=unused-argument - return ( - f"~{self.code_model.core_library}.credentials.{self.policy.credential_name}" - ) + return f"~{self.code_model.core_library}.credentials.{self.policy.credential_name}" def type_annotation(self, **kwargs: Any) -> str: # pylint: disable=unused-argument return self.policy.credential_name diff --git a/packages/autorest.python/autorest/codegen/models/dictionary_type.py b/packages/autorest.python/autorest/codegen/models/dictionary_type.py index 0b9423250fc..bf00b1c2317 100644 --- a/packages/autorest.python/autorest/codegen/models/dictionary_type.py +++ b/packages/autorest.python/autorest/codegen/models/dictionary_type.py @@ -89,19 +89,13 @@ def get_polymorphic_subtypes(self, polymorphic_subtypes: List["ModelType"]) -> N if isinstance(self.element_type, ModelType): is_polymorphic_subtype = ( - self.element_type.discriminator_value - and not self.element_type.discriminated_subtypes + self.element_type.discriminator_value and not self.element_type.discriminated_subtypes ) - if ( - self.element_type.name not in (m.name for m in polymorphic_subtypes) - and is_polymorphic_subtype - ): + if self.element_type.name not in (m.name for m in polymorphic_subtypes) and is_polymorphic_subtype: polymorphic_subtypes.append(self.element_type) @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "DictionaryType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "DictionaryType": """Constructs a DictionaryType from yaml data. :param yaml_data: the yaml data from which we will construct this schema @@ -124,9 +118,7 @@ def from_yaml( def imports(self, **kwargs: Any) -> FileImport: file_import = FileImport(self.code_model) - file_import.add_submodule_import( - "typing", "Dict", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Dict", ImportType.STDLIB, TypingSection.CONDITIONAL) file_import.merge(self.element_type.imports(**kwargs)) return file_import diff --git a/packages/autorest.python/autorest/codegen/models/enum_type.py b/packages/autorest.python/autorest/codegen/models/enum_type.py index a4438527877..6e9c74531c7 100644 --- a/packages/autorest.python/autorest/codegen/models/enum_type.py +++ b/packages/autorest.python/autorest/codegen/models/enum_type.py @@ -78,19 +78,13 @@ def instance_check_template(self) -> str: def imports(self, **kwargs: Any) -> FileImport: file_import = FileImport(self.code_model) file_import.merge(self.value_type.imports(**kwargs)) - file_import.add_submodule_import( - "typing", "Literal", ImportType.STDLIB, TypingSection.REGULAR - ) - file_import.add_submodule_import( - "._enums", self.enum_type.name, ImportType.LOCAL, TypingSection.REGULAR - ) + file_import.add_submodule_import("typing", "Literal", ImportType.STDLIB, TypingSection.REGULAR) + file_import.add_submodule_import("._enums", self.enum_type.name, ImportType.LOCAL, TypingSection.REGULAR) return file_import @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "EnumValue": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "EnumValue": """Constructs an EnumValue from yaml data. :param yaml_data: the yaml data from which we will construct this object @@ -133,9 +127,7 @@ def __init__( self.values = values self.value_type = value_type self.internal: bool = self.yaml_data.get("internal", False) - self.cross_language_definition_id: Optional[str] = self.yaml_data.get( - "crossLanguageDefinitionId" - ) + self.cross_language_definition_id: Optional[str] = self.yaml_data.get("crossLanguageDefinitionId") def __lt__(self, other): return self.name.lower() < other.name.lower() @@ -149,9 +141,7 @@ def serialization_type(self) -> str: """ return self.value_type.serialization_type - def description( - self, *, is_operation_file: bool # pylint: disable=unused-argument - ) -> str: + def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument possible_values = [self.get_declaration(v.value) for v in self.values] if not possible_values: return "" @@ -161,8 +151,7 @@ def description( possible_values_str = " and ".join(possible_values) else: possible_values_str = ( - ", ".join(possible_values[: len(possible_values) - 1]) - + f", and {possible_values[-1]}" + ", ".join(possible_values[: len(possible_values) - 1]) + f", and {possible_values[-1]}" ) enum_description = f"Known values are: {possible_values_str}." @@ -219,16 +208,12 @@ def get_json_template_representation( def instance_check_template(self) -> str: return self.value_type.instance_check_template - def fill_instance_from_yaml( - self, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> None: + def fill_instance_from_yaml(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None: for value in yaml_data["values"]: self.values.append(EnumValue.from_yaml(value, code_model)) @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "EnumType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "EnumType": raise ValueError( "You shouldn't call from_yaml for EnumType to avoid recursion. " "Please initial a blank EnumType, then call .fill_instance_from_yaml on the created type." @@ -238,9 +223,7 @@ def imports(self, **kwargs: Any) -> FileImport: operation = kwargs.pop("operation", False) file_import = FileImport(self.code_model) if self.code_model.options["models_mode"]: - file_import.add_submodule_import( - "typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL) if not operation: file_import.add_submodule_import( "..", @@ -258,10 +241,6 @@ def imports(self, **kwargs: Any) -> FileImport: "models", ImportType.LOCAL, alias="_models", - typing_section=( - TypingSection.TYPING - if kwargs.get("model_typing") - else TypingSection.REGULAR - ), + typing_section=(TypingSection.TYPING if kwargs.get("model_typing") else TypingSection.REGULAR), ) return file_import diff --git a/packages/autorest.python/autorest/codegen/models/imports.py b/packages/autorest.python/autorest/codegen/models/imports.py index 207f12a2b4d..8e21e4b9c1b 100644 --- a/packages/autorest.python/autorest/codegen/models/imports.py +++ b/packages/autorest.python/autorest/codegen/models/imports.py @@ -30,12 +30,8 @@ class TypingSection(str, Enum): class MsrestImportType(Enum): Module = auto() # import _serialization.py or msrest.serialization as Module - Serializer = ( - auto() - ) # from _serialization.py or msrest.serialization import Serializer - SerializerDeserializer = ( - auto() - ) # from _serialization.py or msrest.serialization import Serializer and Deserializer + Serializer = auto() # from _serialization.py or msrest.serialization import Serializer + SerializerDeserializer = auto() # from _serialization.py or msrest.serialization import Serializer and Deserializer class ImportModel: @@ -47,9 +43,7 @@ def __init__( *, submodule_name: Optional[str] = None, alias: Optional[str] = None, - version_modules: Optional[ - Tuple[Tuple[Tuple[int, int], str, Optional[str]]] - ] = None, + version_modules: Optional[Tuple[Tuple[Tuple[int, int], str, Optional[str]]]] = None, ): self.typing_section = typing_section self.import_type = import_type @@ -109,23 +103,15 @@ def _append_import(self, import_model: ImportModel) -> None: ] if all(l not in mod_name for l in core_libraries): # this is to make sure we don't tack on core libraries when we don't need to - import_model.module_name = ( - f"{self.code_model.core_library}{'.' if mod_name else ''}{mod_name}" - ) + import_model.module_name = f"{self.code_model.core_library}{'.' if mod_name else ''}{mod_name}" if not any( i for i in self.imports - if all( - getattr(i, attr) == getattr(import_model, attr) - for attr in dir(i) - if attr[0] != "_" - ) + if all(getattr(i, attr) == getattr(import_model, attr) for attr in dir(i) if attr[0] != "_") ): self.imports.append(import_model) - def get_imports_from_section( - self, typing_section: TypingSection - ) -> List[ImportModel]: + def get_imports_from_section(self, typing_section: TypingSection) -> List[ImportModel]: return [i for i in self.imports if i.typing_section == typing_section] def add_submodule_import( @@ -135,9 +121,7 @@ def add_submodule_import( import_type: ImportType, typing_section: TypingSection = TypingSection.REGULAR, alias: Optional[str] = None, - version_modules: Optional[ - Tuple[Tuple[Tuple[int, int], str, Optional[str]]] - ] = None, + version_modules: Optional[Tuple[Tuple[Tuple[int, int], str, Optional[str]]]] = None, ) -> None: """Add an import to this import block.""" self._append_import( @@ -174,9 +158,7 @@ def define_mypy_type( type_value: str, async_type_value: Optional[str] = None, ): - self.type_definitions[type_name] = TypeDefinition( - type_value, async_type_value or type_value - ) + self.type_definitions[type_name] = TypeDefinition(type_value, async_type_value or type_value) def merge(self, file_import: "FileImport") -> None: """Merge the given file import format.""" @@ -269,9 +251,9 @@ def to_dict( name_import = (i.submodule_name, i.alias) else: name_import = i.submodule_name - retval.setdefault(i.typing_section, {}).setdefault( - i.import_type, {} - ).setdefault(i.module_name, set()).add(name_import) + retval.setdefault(i.typing_section, {}).setdefault(i.import_type, {}).setdefault(i.module_name, set()).add( + name_import + ) return retval def add_msrest_import( @@ -283,24 +265,16 @@ def add_msrest_import( ): if self.code_model.options["client_side_validation"]: if msrest_import_type == MsrestImportType.Module: - self.add_import( - "msrest.serialization", ImportType.SDKCORE, typing_section - ) + self.add_import("msrest.serialization", ImportType.SDKCORE, typing_section) else: - self.add_submodule_import( - "msrest", "Serializer", ImportType.THIRDPARTY, typing_section - ) + self.add_submodule_import("msrest", "Serializer", ImportType.THIRDPARTY, typing_section) if msrest_import_type == MsrestImportType.SerializerDeserializer: - self.add_submodule_import( - "msrest", "Deserializer", ImportType.THIRDPARTY, typing_section - ) + self.add_submodule_import("msrest", "Deserializer", ImportType.THIRDPARTY, typing_section) else: if self.code_model.options["multiapi"]: relative_path += "." if msrest_import_type == MsrestImportType.Module: - self.add_submodule_import( - relative_path, "_serialization", ImportType.LOCAL, typing_section - ) + self.add_submodule_import(relative_path, "_serialization", ImportType.LOCAL, typing_section) else: self.add_submodule_import( f"{relative_path}_serialization", diff --git a/packages/autorest.python/autorest/codegen/models/list_type.py b/packages/autorest.python/autorest/codegen/models/list_type.py index ad477f10e4a..79a2745086f 100644 --- a/packages/autorest.python/autorest/codegen/models/list_type.py +++ b/packages/autorest.python/autorest/codegen/models/list_type.py @@ -69,19 +69,13 @@ def xml_serialization_ctxt(self) -> Optional[str]: return ", ".join(attrs_list) def docstring_type(self, **kwargs: Any) -> str: - if ( - self.code_model.options["version_tolerant"] - and self.element_type.xml_metadata - ): + if self.code_model.options["version_tolerant"] and self.element_type.xml_metadata: # this means we're version tolerant XML, we just return the XML element return self.element_type.docstring_type(**kwargs) return f"list[{self.element_type.docstring_type(**kwargs)}]" def docstring_text(self, **kwargs: Any) -> str: - if ( - self.code_model.options["version_tolerant"] - and self.element_type.xml_metadata - ): + if self.code_model.options["version_tolerant"] and self.element_type.xml_metadata: # this means we're version tolerant XML, we just return the XML element return self.element_type.docstring_text(**kwargs) return f"list of {self.element_type.docstring_text(**kwargs)}" @@ -118,13 +112,9 @@ def get_polymorphic_subtypes(self, polymorphic_subtypes: List["ModelType"]) -> N if isinstance(self.element_type, ModelType): is_polymorphic_subtype = ( - self.element_type.discriminator_value - and not self.element_type.discriminated_subtypes + self.element_type.discriminator_value and not self.element_type.discriminated_subtypes ) - if ( - self.element_type.name not in (m.name for m in polymorphic_subtypes) - and is_polymorphic_subtype - ): + if self.element_type.name not in (m.name for m in polymorphic_subtypes) and is_polymorphic_subtype: polymorphic_subtypes.append(self.element_type) @property @@ -132,17 +122,13 @@ def instance_check_template(self) -> str: return "isinstance({}, list)" @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "ListType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "ListType": from . import build_type return cls( yaml_data=yaml_data, code_model=code_model, - element_type=build_type( - yaml_data=yaml_data["elementType"], code_model=code_model - ), + element_type=build_type(yaml_data=yaml_data["elementType"], code_model=code_model), ) def imports(self, **kwargs: Any) -> FileImport: @@ -152,9 +138,7 @@ def imports(self, **kwargs: Any) -> FileImport: and self.element_type.is_xml and not self.code_model.options["models_mode"] ): - file_import.add_submodule_import( - "typing", "List", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "List", ImportType.STDLIB, TypingSection.CONDITIONAL) file_import.merge(self.element_type.imports(**kwargs)) return file_import diff --git a/packages/autorest.python/autorest/codegen/models/lro_operation.py b/packages/autorest.python/autorest/codegen/models/lro_operation.py index cfca6acac22..2e127df9d3b 100644 --- a/packages/autorest.python/autorest/codegen/models/lro_operation.py +++ b/packages/autorest.python/autorest/codegen/models/lro_operation.py @@ -17,9 +17,7 @@ from .client import Client from . import OperationType -LROResponseType = TypeVar( - "LROResponseType", bound=Union[LROResponse, LROPagingResponse] -) +LROResponseType = TypeVar("LROResponseType", bound=Union[LROResponse, LROPagingResponse]) class LROOperationBase(OperationBase[LROResponseType]): @@ -55,9 +53,7 @@ def __init__( @property def initial_operation(self) -> "OperationType": if not self._initial_operation: - raise ValueError( - "You need to first call client.link_lro_initial_operations before accessing" - ) + raise ValueError("You need to first call client.link_lro_initial_operations before accessing") return self._initial_operation @initial_operation.setter @@ -75,16 +71,12 @@ def has_optional_return_type(self) -> bool: @property def lro_response(self) -> Optional[LROResponseType]: responses_with_bodies = [r for r in self.responses if r.type] - num_response_schemas = { - id(r.type.yaml_data) for r in responses_with_bodies if r.type - } + num_response_schemas = {id(r.type.yaml_data) for r in responses_with_bodies if r.type} response = None if len(num_response_schemas) > 1: # choose the response that has a status code of 200 try: - response = next( - r for r in responses_with_bodies if 200 in r.status_codes - ) + response = next(r for r in responses_with_bodies if 200 in r.status_codes) except StopIteration as exc: raise ValueError( "Your swagger is invalid because you have multiple response schemas for LRO" @@ -142,12 +134,8 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: # used in the case if initial operation returns none # but final call returns a model relative_path = "..." if async_mode else ".." - file_import.add_submodule_import( - f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL - ) - file_import.add_submodule_import( - "typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL) + file_import.add_submodule_import("typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL) file_import.add_submodule_import("typing", "cast", ImportType.STDLIB) return file_import diff --git a/packages/autorest.python/autorest/codegen/models/lro_paging_operation.py b/packages/autorest.python/autorest/codegen/models/lro_paging_operation.py index d663a37e317..42c885f308f 100644 --- a/packages/autorest.python/autorest/codegen/models/lro_paging_operation.py +++ b/packages/autorest.python/autorest/codegen/models/lro_paging_operation.py @@ -10,9 +10,7 @@ from .response import LROPagingResponse, Response -class LROPagingOperation( - LROOperationBase[LROPagingResponse], PagingOperationBase[LROPagingResponse] -): +class LROPagingOperation(LROOperationBase[LROPagingResponse], PagingOperationBase[LROPagingResponse]): @property def success_status_codes(self): """The list of all successfull status code.""" diff --git a/packages/autorest.python/autorest/codegen/models/model_type.py b/packages/autorest.python/autorest/codegen/models/model_type.py index b126b9610e9..f113ac7604b 100644 --- a/packages/autorest.python/autorest/codegen/models/model_type.py +++ b/packages/autorest.python/autorest/codegen/models/model_type.py @@ -30,13 +30,8 @@ def _get_properties(type: "ModelType", properties: List[Property]) -> List[Prope # need to make sure that the properties we choose from our parent also don't contain # any of our own properties - property_names = set( - [p.client_name for p in properties] - + [p.client_name for p in type.properties] - ) - chosen_parent_properties = [ - p for p in parent.properties if p.client_name not in property_names - ] + property_names = set([p.client_name for p in properties] + [p.client_name for p in type.properties]) + chosen_parent_properties = [p for p in parent.properties if p.client_name not in property_names] properties = _get_properties(parent, chosen_parent_properties) + properties return properties @@ -70,17 +65,13 @@ def __init__( self.properties = properties or [] self.parents = parents or [] self.discriminated_subtypes = discriminated_subtypes or {} - self.discriminator_value: Optional[str] = self.yaml_data.get( - "discriminatorValue" - ) + self.discriminator_value: Optional[str] = self.yaml_data.get("discriminatorValue") self._created_json_template_representation = False self._got_polymorphic_subtypes = False self.internal: bool = self.yaml_data.get("internal", False) self.snake_case_name: str = self.yaml_data["snakeCaseName"] self.page_result_model: bool = self.yaml_data.get("pageResultModel", False) - self.cross_language_definition_id: Optional[str] = self.yaml_data.get( - "crossLanguageDefinitionId" - ) + self.cross_language_definition_id: Optional[str] = self.yaml_data.get("crossLanguageDefinitionId") @property def flattened_property(self) -> Optional[Property]: @@ -151,11 +142,7 @@ def get_json_template_representation( if self.discriminated_subtypes: # we will instead print the discriminated subtypes self._created_json_template_representation = False - return ( - f'"{self.snake_case_name}"' - if self.code_model.for_test - else self.snake_case_name - ) + return f'"{self.snake_case_name}"' if self.code_model.for_test else self.snake_case_name # don't add additional properties, because there's not really a concept of # additional properties in the template @@ -166,22 +153,16 @@ def get_json_template_representation( description=description, ) for prop in [ - p - for p in self.properties - if not (p.is_discriminator or p.client_name == "additional_properties") + p for p in self.properties if not (p.is_discriminator or p.client_name == "additional_properties") ] } if self.discriminator and self.discriminator_value: - representation[f'"{self.discriminator.wire_name}"'] = ( - f'"{self.discriminator_value}"' - ) + representation[f'"{self.discriminator.wire_name}"'] = f'"{self.discriminator_value}"' # once we've finished, we want to reset created_json_template_representation to false # so we can call it again self._created_json_template_representation = False - optional_keys = [ - f'"{p.wire_name}"' for p in self.properties if getattr(p, "optional", False) - ] + optional_keys = [f'"{p.wire_name}"' for p in self.properties if getattr(p, "optional", False)] return OrderedDict( sorted( representation.items(), @@ -190,16 +171,11 @@ def get_json_template_representation( ) def get_polymorphic_subtypes(self, polymorphic_subtypes: List["ModelType"]) -> None: - is_polymorphic_subtype = ( - self.discriminator_value and not self.discriminated_subtypes - ) + is_polymorphic_subtype = self.discriminator_value and not self.discriminated_subtypes if self._got_polymorphic_subtypes: return self._got_polymorphic_subtypes = True - if ( - self.name not in (m.name for m in polymorphic_subtypes) - and is_polymorphic_subtype - ): + if self.name not in (m.name for m in polymorphic_subtypes) and is_polymorphic_subtype: polymorphic_subtypes.append(self) for discriminated_subtype in self.discriminated_subtypes.values(): discriminated_subtype.get_polymorphic_subtypes(polymorphic_subtypes) @@ -208,26 +184,17 @@ def get_polymorphic_subtypes(self, polymorphic_subtypes: List["ModelType"]) -> N self._got_polymorphic_subtypes = False @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "ModelType": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "ModelType": raise ValueError( "You shouldn't call from_yaml for ModelType to avoid recursion. " "Please initial a blank ModelType, then call .fill_instance_from_yaml on the created type." ) - def fill_instance_from_yaml( - self, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> None: + def fill_instance_from_yaml(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None: from . import build_type - self.parents = [ - cast(ModelType, build_type(bm, code_model)) - for bm in yaml_data.get("parents", []) - ] - properties = [ - Property.from_yaml(p, code_model) for p in yaml_data["properties"] - ] + self.parents = [cast(ModelType, build_type(bm, code_model)) for bm in yaml_data.get("parents", [])] + properties = [Property.from_yaml(p, code_model) for p in yaml_data["properties"]] self.properties = _get_properties(self, properties) # checking to see if this is a polymorphic class self.discriminated_subtypes = { @@ -237,10 +204,7 @@ def fill_instance_from_yaml( @property def has_readonly_or_constant_property(self) -> bool: - return any( - x.readonly or x.constant or x.visibility == ["read"] - for x in self.properties - ) + return any(x.readonly or x.constant or x.visibility == ["read"] for x in self.properties) @property def discriminator(self) -> Optional[Property]: @@ -255,9 +219,7 @@ def discriminator_property(self) -> Optional[Property]: return next( p for p in self.properties - if p.is_discriminator - and isinstance(p.type, ConstantType) - and p.type.value == self.discriminator_value + if p.is_discriminator and isinstance(p.type, ConstantType) and p.type.value == self.discriminator_value ) except StopIteration: return None @@ -301,14 +263,10 @@ def instance_check_template(self) -> str: def imports(self, **kwargs: Any) -> FileImport: file_import = FileImport(self.code_model) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) file_import.define_mutable_mapping_type() if self.is_xml: - file_import.add_submodule_import( - "xml.etree", "ElementTree", ImportType.STDLIB, alias="ET" - ) + file_import.add_submodule_import("xml.etree", "ElementTree", ImportType.STDLIB, alias="ET") return file_import @@ -341,22 +299,14 @@ def imports(self, **kwargs: Any) -> FileImport: "models", ImportType.LOCAL, alias="_models", - typing_section=( - TypingSection.TYPING - if kwargs.get("model_typing") - else TypingSection.REGULAR - ), + typing_section=(TypingSection.TYPING if kwargs.get("model_typing") else TypingSection.REGULAR), ) if self.is_form_data: file_import.add_submodule_import( relative_path, "_model_base", ImportType.LOCAL, - typing_section=( - TypingSection.TYPING - if kwargs.get("model_typing") - else TypingSection.REGULAR - ), + typing_section=(TypingSection.TYPING if kwargs.get("model_typing") else TypingSection.REGULAR), ) return file_import @@ -374,9 +324,7 @@ def instance_check_template(self) -> str: def imports(self, **kwargs: Any) -> FileImport: file_import = super().imports(**kwargs) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) return file_import diff --git a/packages/autorest.python/autorest/codegen/models/operation.py b/packages/autorest.python/autorest/codegen/models/operation.py index b1cc8aea26d..09136058537 100644 --- a/packages/autorest.python/autorest/codegen/models/operation.py +++ b/packages/autorest.python/autorest/codegen/models/operation.py @@ -83,17 +83,13 @@ def __init__( self.request_builder = request_builder self.deprecated = False self.exceptions = exceptions - self.is_lro_initial_operation: bool = self.yaml_data.get( - "isLroInitialOperation", False - ) + self.is_lro_initial_operation: bool = self.yaml_data.get("isLroInitialOperation", False) self.include_documentation: bool = not self.is_lro_initial_operation self.internal: bool = self.yaml_data.get("internal", False) if self.internal: self.name = "_" + self.name self.has_etag: bool = self.yaml_data.get("hasEtag", False) - self.cross_language_definition_id: Optional[str] = self.yaml_data.get( - "crossLanguageDefinitionId" - ) + self.cross_language_definition_id: Optional[str] = self.yaml_data.get("crossLanguageDefinitionId") @property def has_form_data_body(self): @@ -118,15 +114,10 @@ def has_optional_return_type(self) -> bool: return successful_response_with_body and successful_response_without_body def response_type_annotation(self, **kwargs) -> str: - if ( - self.code_model.options["head_as_boolean"] - and self.request_builder.method.lower() == "head" - ): + if self.code_model.options["head_as_boolean"] and self.request_builder.method.lower() == "head": return "bool" response_type_annotations: OrderedSet[str] = { - response.type_annotation(**kwargs): None - for response in self.responses - if response.type + response.type_annotation(**kwargs): None for response in self.responses if response.type } response_str = ", ".join(response_type_annotations.keys()) if len(response_type_annotations) > 1: @@ -144,9 +135,7 @@ def pylint_disable(self) -> str: # doesn't matter if it's async or not retval = add_to_pylint_disable(retval, "inconsistent-return-statements") try: - if any(is_internal(r.type) for r in self.responses) or is_internal( - self.parameters.body_parameter.type - ): + if any(is_internal(r.type) for r in self.responses) or is_internal(self.parameters.body_parameter.type): retval = add_to_pylint_disable(retval, "protected-access") except ValueError: pass @@ -155,24 +144,17 @@ def pylint_disable(self) -> str: return retval def cls_type_annotation(self, *, async_mode: bool) -> str: - if ( - self.request_builder.method.lower() == "head" - and self.code_model.options["head_as_boolean"] - ): + if self.request_builder.method.lower() == "head" and self.code_model.options["head_as_boolean"]: return "ClsType[None]" return f"ClsType[{self.response_type_annotation(async_mode=async_mode)}]" def _response_docstring_helper(self, attr_name: str, **kwargs: Any) -> str: responses_with_body = [r for r in self.responses if r.type] - if ( - self.request_builder.method.lower() == "head" - and self.code_model.options["head_as_boolean"] - ): + if self.request_builder.method.lower() == "head" and self.code_model.options["head_as_boolean"]: return "bool" if responses_with_body: response_docstring_values: OrderedSet[str] = { - getattr(response, attr_name)(**kwargs): None - for response in responses_with_body + getattr(response, attr_name)(**kwargs): None for response in responses_with_body } retval = " or ".join(response_docstring_values.keys()) if self.has_optional_return_type: @@ -210,9 +192,7 @@ def any_response_has_headers(self) -> bool: @property def default_error_deserialization(self) -> Optional[str]: - default_exceptions = [ - e for e in self.exceptions if "default" in e.status_codes and e.type - ] + default_exceptions = [e for e in self.exceptions if "default" in e.status_codes and e.type] if not default_exceptions: return None excep_schema = default_exceptions[0].type @@ -228,29 +208,15 @@ def non_default_errors(self) -> List[Response]: @property def non_default_error_status_codes(self) -> List[Union[str, int]]: """Actually returns all of the status codes from exceptions (besides default)""" - return list( - chain.from_iterable( - [error.status_codes for error in self.non_default_errors] - ) - ) + return list(chain.from_iterable([error.status_codes for error in self.non_default_errors])) - def _imports_shared( - self, async_mode: bool, **kwargs: Any # pylint: disable=unused-argument - ) -> FileImport: + def _imports_shared(self, async_mode: bool, **kwargs: Any) -> FileImport: # pylint: disable=unused-argument file_import = FileImport(self.code_model) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) - response_types = [ - r.type_annotation(async_mode=async_mode, operation=self) - for r in self.responses - if r.type - ] + response_types = [r.type_annotation(async_mode=async_mode, operation=self) for r in self.responses if r.type] if len(set(response_types)) > 1: - file_import.add_submodule_import( - "typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL) if self.added_on: file_import.add_submodule_import( f"{'.' if async_mode else ''}.._validation", @@ -272,18 +238,10 @@ def imports_for_multiapi(self, async_mode: bool, **kwargs: Any) -> FileImport: ) ) for response in self.responses: - file_import.merge( - response.imports_for_multiapi( - async_mode=async_mode, operation=self, **kwargs - ) - ) + file_import.merge(response.imports_for_multiapi(async_mode=async_mode, operation=self, **kwargs)) if self.code_model.options["models_mode"]: for exception in self.exceptions: - file_import.merge( - exception.imports_for_multiapi( - async_mode=async_mode, operation=self, **kwargs - ) - ) + file_import.merge(exception.imports_for_multiapi(async_mode=async_mode, operation=self, **kwargs)) return file_import @staticmethod @@ -298,9 +256,7 @@ def has_kwargs_to_pop_with_default( location: ParameterLocation, ) -> bool: return any( - (kwarg.client_default_value or kwarg.optional) - and kwarg.location == location - for kwarg in kwargs_to_pop + (kwarg.client_default_value or kwarg.optional) and kwarg.location == location for kwarg in kwargs_to_pop ) @property @@ -356,17 +312,13 @@ def imports( # pylint: disable=too-many-branches, disable=too-many-statements ) ) for response in self.responses: - file_import.merge( - response.imports(async_mode=async_mode, operation=self, **kwargs) - ) + file_import.merge(response.imports(async_mode=async_mode, operation=self, **kwargs)) if self.code_model.options["models_mode"]: for exception in self.exceptions: file_import.merge(exception.imports(async_mode=async_mode, **kwargs)) if self.parameters.has_body and self.parameters.body_parameter.flattened: - file_import.merge( - self.parameters.body_parameter.type.imports(operation=self, **kwargs) - ) + file_import.merge(self.parameters.body_parameter.type.imports(operation=self, **kwargs)) if not async_mode: for param in self.parameters.headers: if param.wire_name.lower() == "repeatability-request-id": @@ -386,9 +338,7 @@ def imports( # pylint: disable=too-many-branches, disable=too-many-statements for error in errors: file_import.add_submodule_import("exceptions", error, ImportType.SDKCORE) if self.code_model.options["azure_arm"]: - file_import.add_submodule_import( - "azure.mgmt.core.exceptions", "ARMErrorFormat", ImportType.SDKCORE - ) + file_import.add_submodule_import("azure.mgmt.core.exceptions", "ARMErrorFormat", ImportType.SDKCORE) file_import.add_submodule_import( "typing", "Type", @@ -417,9 +367,7 @@ def imports( # pylint: disable=too-many-branches, disable=too-many-statements relative_path = "..." if async_mode else ".." if self.code_model.need_request_converter: - file_import.add_submodule_import( - f"{relative_path}_vendor", "_convert_request", ImportType.LOCAL - ) + file_import.add_submodule_import(f"{relative_path}_vendor", "_convert_request", ImportType.LOCAL) if self.has_etag: file_import.add_submodule_import( "exceptions", @@ -427,12 +375,8 @@ def imports( # pylint: disable=too-many-branches, disable=too-many-statements ImportType.SDKCORE, ) if not async_mode: - file_import.add_submodule_import( - f"{relative_path}_vendor", "prep_if_match", ImportType.LOCAL - ) - file_import.add_submodule_import( - f"{relative_path}_vendor", "prep_if_none_match", ImportType.LOCAL - ) + file_import.add_submodule_import(f"{relative_path}_vendor", "prep_if_match", ImportType.LOCAL) + file_import.add_submodule_import(f"{relative_path}_vendor", "prep_if_none_match", ImportType.LOCAL) if self.code_model.need_request_converter: if async_mode: file_import.add_submodule_import( @@ -459,10 +403,7 @@ def imports( # pylint: disable=too-many-branches, disable=too-many-statements "HttpResponse", ImportType.SDKCORE, ) - if ( - self.code_model.options["builders_visibility"] == "embedded" - and not async_mode - ): + if self.code_model.options["builders_visibility"] == "embedded" and not async_mode: file_import.merge(self.request_builder.imports()) file_import.add_submodule_import( f"{'' if self.code_model.is_azure_flavor else 'runtime.'}pipeline", @@ -470,51 +411,33 @@ def imports( # pylint: disable=too-many-branches, disable=too-many-statements ImportType.SDKCORE, ) file_import.add_submodule_import("rest", "HttpRequest", ImportType.SDKCORE) - file_import.add_submodule_import( - "typing", "Callable", ImportType.STDLIB, TypingSection.CONDITIONAL - ) - file_import.add_submodule_import( - "typing", "Optional", ImportType.STDLIB, TypingSection.CONDITIONAL - ) - file_import.add_submodule_import( - "typing", "Dict", ImportType.STDLIB, TypingSection.CONDITIONAL - ) - file_import.add_submodule_import( - "typing", "TypeVar", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Callable", ImportType.STDLIB, TypingSection.CONDITIONAL) + file_import.add_submodule_import("typing", "Optional", ImportType.STDLIB, TypingSection.CONDITIONAL) + file_import.add_submodule_import("typing", "Dict", ImportType.STDLIB, TypingSection.CONDITIONAL) + file_import.add_submodule_import("typing", "TypeVar", ImportType.STDLIB, TypingSection.CONDITIONAL) if self.code_model.options["tracing"] and self.want_tracing and not async_mode: file_import.add_submodule_import( "azure.core.tracing.decorator", "distributed_trace", ImportType.SDKCORE, ) - file_import.merge( - self.get_request_builder_import(self.request_builder, async_mode) - ) + file_import.merge(self.get_request_builder_import(self.request_builder, async_mode)) if self.overloads: file_import.add_submodule_import("typing", "overload", ImportType.STDLIB) if self.non_default_errors and self.code_model.options["models_mode"] == "dpg": - file_import.add_submodule_import( - f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL - ) + file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL) return file_import - def get_response_from_status( - self, status_code: Optional[Union[str, int]] - ) -> ResponseType: + def get_response_from_status(self, status_code: Optional[Union[str, int]]) -> ResponseType: try: return next(r for r in self.responses if status_code in r.status_codes) except StopIteration as exc: - raise ValueError( - f"Incorrect status code {status_code}, operation {self.name}" - ) from exc + raise ValueError(f"Incorrect status code {status_code}, operation {self.name}") from exc @property def success_status_codes(self) -> Sequence[Union[str, int]]: """The list of all successfull status code.""" - return sorted( - [code for response in self.responses for code in response.status_codes] - ) + return sorted([code for response in self.responses for code in response.status_codes]) @property def filename(self) -> str: @@ -523,10 +446,7 @@ def filename(self) -> str: # in a mixin basename = self.code_model.clients[0].legacy_filename - if ( - basename == "operations" - or self.code_model.options["combine_operation_files"] - ): + if basename == "operations" or self.code_model.options["combine_operation_files"]: return "_operations" return f"_{basename}_operations" @@ -547,18 +467,10 @@ def from_yaml( ): name = yaml_data["name"] request_builder = cls.get_request_builder(yaml_data, client) - responses = [ - cast(ResponseType, get_response(r, code_model)) - for r in yaml_data["responses"] - ] - exceptions = [ - Response.from_yaml(e, code_model) for e in yaml_data["exceptions"] - ] + responses = [cast(ResponseType, get_response(r, code_model)) for r in yaml_data["responses"]] + exceptions = [Response.from_yaml(e, code_model) for e in yaml_data["exceptions"]] parameter_list = ParameterList.from_yaml(yaml_data, code_model) - overloads = [ - cls.from_yaml(overload, code_model, client) - for overload in yaml_data.get("overloads", []) - ] + overloads = [cls.from_yaml(overload, code_model, client) for overload in yaml_data.get("overloads", [])] return cls( yaml_data=yaml_data, @@ -584,11 +496,7 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: "distributed_trace_async", ImportType.SDKCORE, ) - if ( - self.has_response_body - and not self.has_optional_return_type - and not self.code_model.options["models_mode"] - ): + if self.has_response_body and not self.has_optional_return_type and not self.code_model.options["models_mode"]: file_import.add_submodule_import("typing", "cast", ImportType.STDLIB) relative_path = "..." if async_mode else ".." if self.code_model.options["models_mode"] == "dpg": @@ -600,19 +508,13 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: ImportType.LOCAL, ) file_import.add_import("json", ImportType.STDLIB) - if self.default_error_deserialization or any( - r.type for r in self.responses - ): - file_import.add_submodule_import( - f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL - ) + if self.default_error_deserialization or any(r.type for r in self.responses): + file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL) return file_import -def get_operation( - yaml_data: Dict[str, Any], code_model: "CodeModel", client: "Client" -) -> "OperationType": +def get_operation(yaml_data: Dict[str, Any], code_model: "CodeModel", client: "Client") -> "OperationType": if yaml_data["discriminator"] == "lropaging": from .lro_paging_operation import LROPagingOperation as OperationCls elif yaml_data["discriminator"] == "lro": diff --git a/packages/autorest.python/autorest/codegen/models/operation_group.py b/packages/autorest.python/autorest/codegen/models/operation_group.py index 339807d9622..bf890b6565e 100644 --- a/packages/autorest.python/autorest/codegen/models/operation_group.py +++ b/packages/autorest.python/autorest/codegen/models/operation_group.py @@ -49,15 +49,13 @@ def __init__( @property def has_abstract_operations(self) -> bool: return any(o for o in self.operations if o.abstract) or any( - operation_group.has_abstract_operations - for operation_group in self.operation_groups + operation_group.has_abstract_operations for operation_group in self.operation_groups ) @property def has_non_abstract_operations(self) -> bool: return any(o for o in self.operations if not o.abstract) or any( - operation_group.has_non_abstract_operations - for operation_group in self.operation_groups + operation_group.has_non_abstract_operations for operation_group in self.operation_groups ) @property @@ -71,15 +69,11 @@ def imports_for_multiapi(self, async_mode: bool) -> FileImport: file_import = FileImport(self.code_model) relative_path = ".." if async_mode else "." for operation in self.operations: - file_import.merge( - operation.imports_for_multiapi(async_mode, relative_path=relative_path) - ) - if ( - self.code_model.model_types or self.code_model.enums - ) and self.code_model.options["models_mode"] == "msrest": - file_import.add_submodule_import( - relative_path, "models", ImportType.LOCAL, alias="_models" - ) + file_import.merge(operation.imports_for_multiapi(async_mode, relative_path=relative_path)) + if (self.code_model.model_types or self.code_model.enums) and self.code_model.options[ + "models_mode" + ] == "msrest": + file_import.add_submodule_import(relative_path, "models", ImportType.LOCAL, alias="_models") return file_import @property @@ -103,13 +97,9 @@ def need_validation(self) -> bool: def imports(self, async_mode: bool) -> FileImport: file_import = FileImport(self.code_model) - relative_path = ("..." if async_mode else "..") + ( - "." if self.client.is_subclient else "" - ) + relative_path = ("..." if async_mode else "..") + ("." if self.client.is_subclient else "") for operation in self.operations: - file_import.merge( - operation.imports(async_mode, relative_path=relative_path) - ) + file_import.merge(operation.imports(async_mode, relative_path=relative_path)) if not self.code_model.options["combine_operation_files"]: for og in self.operation_groups: file_import.add_submodule_import( @@ -123,27 +113,17 @@ def imports(self, async_mode: bool) -> FileImport: and self.code_model.options["models_mode"] == "msrest" and not self.is_mixin ): - file_import.add_submodule_import( - relative_path, "models", ImportType.LOCAL, alias="_models" - ) + file_import.add_submodule_import(relative_path, "models", ImportType.LOCAL, alias="_models") if self.code_model.need_mixin_abc: - file_import.add_submodule_import( - ".._vendor", f"{self.client.name}MixinABC", ImportType.LOCAL - ) + file_import.add_submodule_import(".._vendor", f"{self.client.name}MixinABC", ImportType.LOCAL) if self.has_abstract_operations: - file_import.add_submodule_import( - ".._vendor", "raise_if_not_implemented", ImportType.LOCAL - ) + file_import.add_submodule_import(".._vendor", "raise_if_not_implemented", ImportType.LOCAL) if all(o.abstract for o in self.operations): return file_import - file_import.add_submodule_import( - "typing", "TypeVar", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "TypeVar", ImportType.STDLIB, TypingSection.CONDITIONAL) file_import.define_mypy_type("T", "TypeVar('T')") type_value = "Optional[Callable[[PipelineResponse[HttpRequest, {}HttpResponse], T, Dict[str, Any]], Any]]" - file_import.define_mypy_type( - "ClsType", type_value.format(""), type_value.format("Async") - ) + file_import.define_mypy_type("ClsType", type_value.format(""), type_value.format("Async")) return file_import @property @@ -160,44 +140,27 @@ def link_lro_initial_operations(self) -> None: for operation_group in self.operation_groups: for operation in operation_group.operations: if isinstance(operation, (LROOperation, LROPagingOperation)): - operation.initial_operation = self.lookup_operation( - id(operation.yaml_data["initialOperation"]) - ) + operation.initial_operation = self.lookup_operation(id(operation.yaml_data["initialOperation"])) def lookup_operation(self, operation_id: int) -> "OperationType": try: - return next( - o - for og in self.operation_groups - for o in og.operations - if id(o.yaml_data) == operation_id - ) + return next(o for og in self.operation_groups for o in og.operations if id(o.yaml_data) == operation_id) except StopIteration as exc: raise KeyError(f"No operation with id {operation_id} found.") from exc @property def lro_operations(self) -> List["OperationType"]: - return [ - operation - for operation in self.operations - if operation.operation_type in ("lro", "lropaging") - ] + [ - operation - for operation_group in self.operation_groups - for operation in operation_group.lro_operations + return [operation for operation in self.operations if operation.operation_type in ("lro", "lropaging")] + [ + operation for operation_group in self.operation_groups for operation in operation_group.lro_operations ] @property def has_operations(self) -> bool: - return any( - operation_group.has_operations for operation_group in self.operation_groups - ) or bool(self.operations) + return any(operation_group.has_operations for operation_group in self.operation_groups) or bool(self.operations) @property def has_form_data_body(self) -> bool: - operations = self.operations + [ - o for og in self.operation_groups for o in og.operations - ] + operations = self.operations + [o for og in self.operation_groups for o in og.operations] return any(operation.has_form_data_body for operation in operations) @classmethod @@ -207,9 +170,7 @@ def from_yaml( code_model: "CodeModel", client: "Client", ) -> "OperationGroup": - operations = [ - get_operation(o, code_model, client) for o in yaml_data["operations"] - ] + operations = [get_operation(o, code_model, client) for o in yaml_data["operations"]] api_versions: OrderedSet[str] = {} for operation in operations: for api_version in operation.api_versions: diff --git a/packages/autorest.python/autorest/codegen/models/paging_operation.py b/packages/autorest.python/autorest/codegen/models/paging_operation.py index 4391d93c54e..554b72d4431 100644 --- a/packages/autorest.python/autorest/codegen/models/paging_operation.py +++ b/packages/autorest.python/autorest/codegen/models/paging_operation.py @@ -22,9 +22,7 @@ from .code_model import CodeModel from .client import Client -PagingResponseType = TypeVar( - "PagingResponseType", bound=Union[PagingResponse, LROPagingResponse] -) +PagingResponseType = TypeVar("PagingResponseType", bound=Union[PagingResponse, LROPagingResponse]) class PagingOperationBase(OperationBase[PagingResponseType]): @@ -53,41 +51,25 @@ def __init__( exceptions=exceptions, overloads=overloads, ) - self.next_request_builder: Optional[ - Union[RequestBuilder, OverloadedRequestBuilder] - ] = ( + self.next_request_builder: Optional[Union[RequestBuilder, OverloadedRequestBuilder]] = ( get_request_builder(self.yaml_data["nextOperation"], code_model, client) if self.yaml_data.get("nextOperation") else None ) self.override_success_response_to_200 = override_success_response_to_200 - self.pager_sync: str = ( - yaml_data.get("pagerSync") - or f"{self.code_model.core_library}.paging.ItemPaged" - ) - self.pager_async: str = ( - yaml_data.get("pagerAsync") - or f"{self.code_model.core_library}.paging.AsyncItemPaged" - ) + self.pager_sync: str = yaml_data.get("pagerSync") or f"{self.code_model.core_library}.paging.ItemPaged" + self.pager_async: str = yaml_data.get("pagerAsync") or f"{self.code_model.core_library}.paging.AsyncItemPaged" def _get_attr_name(self, wire_name: str) -> str: response_type = self.responses[0].type if not response_type: - raise ValueError( - f"Can't find a matching property in response for {wire_name}" - ) + raise ValueError(f"Can't find a matching property in response for {wire_name}") if response_type.type == "list": response_type = cast(ListType, response_type).element_type try: - return next( - p.client_name - for p in cast(ModelType, response_type).properties - if p.wire_name == wire_name - ) + return next(p.client_name for p in cast(ModelType, response_type).properties if p.wire_name == wire_name) except StopIteration as exc: - raise ValueError( - f"Can't find a matching property in response for {wire_name}" - ) from exc + raise ValueError(f"Can't find a matching property in response for {wire_name}") from exc def get_pager(self, async_mode: bool) -> str: return self.responses[0].get_pager(async_mode) @@ -115,9 +97,7 @@ def item_type(self) -> ModelType: try: item_type_yaml = self.yaml_data["itemType"] except KeyError as e: - raise ValueError( - "Only call this for DPG paging model deserialization" - ) from e + raise ValueError("Only call this for DPG paging model deserialization") from e return cast(ModelType, self.code_model.types_map[id(item_type_yaml)]) @property @@ -130,13 +110,9 @@ def cls_type_annotation(self, *, async_mode: bool) -> str: def _imports_shared(self, async_mode: bool, **kwargs: Any) -> FileImport: file_import = super()._imports_shared(async_mode, **kwargs) if async_mode: - file_import.add_submodule_import( - "typing", "AsyncIterable", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "AsyncIterable", ImportType.STDLIB, TypingSection.CONDITIONAL) else: - file_import.add_submodule_import( - "typing", "Iterable", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Iterable", ImportType.STDLIB, TypingSection.CONDITIONAL) if ( self.next_request_builder and self.code_model.options["builders_visibility"] == "embedded" @@ -161,9 +137,7 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: ImportType.SDKCORE, ) if self.next_request_builder: - file_import.merge( - self.get_request_builder_import(self.next_request_builder, async_mode) - ) + file_import.merge(self.get_request_builder_import(self.next_request_builder, async_mode)) elif any(p.is_api_version for p in self.client.parameters): file_import.add_import("urllib.parse", ImportType.STDLIB) file_import.add_submodule_import( @@ -174,12 +148,8 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: if self.code_model.options["models_mode"] == "dpg": relative_path = "..." if async_mode else ".." file_import.merge(self.item_type.imports(**kwargs)) - if self.default_error_deserialization or any( - r.type for r in self.responses - ): - file_import.add_submodule_import( - f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL - ) + if self.default_error_deserialization or any(r.type for r in self.responses): + file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL) return file_import diff --git a/packages/autorest.python/autorest/codegen/models/parameter.py b/packages/autorest.python/autorest/codegen/models/parameter.py index 88dffcc680c..296c8386008 100644 --- a/packages/autorest.python/autorest/codegen/models/parameter.py +++ b/packages/autorest.python/autorest/codegen/models/parameter.py @@ -51,9 +51,7 @@ class ParameterDelimeter(str, Enum): COMMA = "comma" -class _ParameterBase( - BaseModel, abc.ABC -): # pylint: disable=too-many-instance-attributes +class _ParameterBase(BaseModel, abc.ABC): # pylint: disable=too-many-instance-attributes """Base class for all parameters""" def __init__( @@ -77,9 +75,7 @@ def __init__( self.grouped_by: Optional[str] = self.yaml_data.get("groupedBy") # property matching property name to parameter name for grouping params # and flattened body params - self.property_to_parameter_name: Optional[Dict[str, str]] = self.yaml_data.get( - "propertyToParameterName" - ) + self.property_to_parameter_name: Optional[Dict[str, str]] = self.yaml_data.get("propertyToParameterName") self.flattened: bool = self.yaml_data.get("flattened", False) self.in_flattened_body: bool = self.yaml_data.get("inFlattenedBody", False) self.grouper: bool = self.yaml_data.get("grouper", False) @@ -87,9 +83,7 @@ def __init__( self.added_on: Optional[str] = self.yaml_data.get("addedOn") self.is_api_version: bool = self.yaml_data.get("isApiVersion", False) self.in_overload: bool = self.yaml_data.get("inOverload", False) - self.default_to_unset_sentinel: bool = self.yaml_data.get( - "defaultToUnsetSentinel", False - ) + self.default_to_unset_sentinel: bool = self.yaml_data.get("defaultToUnsetSentinel", False) self.hide_in_method: bool = self.yaml_data.get("hideInMethod", False) def get_declaration(self, value: Any = None) -> Any: @@ -105,9 +99,7 @@ def constant(self) -> bool: Checking to see if it's required, because if not, we don't consider it a constant because it can have a value of None. """ - return (not self.optional or self.is_api_version) and isinstance( - self.type, ConstantType - ) + return (not self.optional or self.is_api_version) and isinstance(self.type, ConstantType) @property def description(self) -> str: @@ -201,9 +193,7 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: def imports_for_multiapi(self, async_mode: bool, **kwargs: Any) -> FileImport: file_import = self._imports_shared(async_mode, **kwargs) - file_import.merge( - self.type.imports_for_multiapi(async_mode=async_mode, **kwargs) - ) + file_import.merge(self.type.imports_for_multiapi(async_mode=async_mode, **kwargs)) return file_import @property @@ -212,19 +202,11 @@ def method_location(self) -> ParameterMethodLocation: @property def description_keyword(self) -> str: - return ( - "param" - if self.method_location == ParameterMethodLocation.POSITIONAL - else "keyword" - ) + return "param" if self.method_location == ParameterMethodLocation.POSITIONAL else "keyword" @property def docstring_type_keyword(self) -> str: - return ( - "type" - if self.method_location == ParameterMethodLocation.POSITIONAL - else "paramtype" - ) + return "type" if self.method_location == ParameterMethodLocation.POSITIONAL else "paramtype" @property @abc.abstractmethod @@ -244,10 +226,7 @@ class BodyParameter(_ParameterBase): @property def entries(self) -> List["BodyParameter"]: - return [ - BodyParameter.from_yaml(e, self.code_model) - for e in self.yaml_data.get("entries", []) - ] + return [BodyParameter.from_yaml(e, self.code_model) for e in self.yaml_data.get("entries", [])] @property def is_form_data(self) -> bool: @@ -262,11 +241,7 @@ def is_partial_body(self) -> bool: @property def method_location(self) -> ParameterMethodLocation: - return ( - ParameterMethodLocation.KWARG - if self.constant - else ParameterMethodLocation.POSITIONAL - ) + return ParameterMethodLocation.KWARG if self.constant else ParameterMethodLocation.POSITIONAL @property def in_method_signature(self) -> bool: @@ -303,9 +278,7 @@ def imports(self, async_mode: bool, **kwargs: Any) -> FileImport: return file_import @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "BodyParameter": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "BodyParameter": return cls( yaml_data=yaml_data, code_model=code_model, @@ -313,9 +286,7 @@ def from_yaml( ) -EntryBodyParameterType = TypeVar( - "EntryBodyParameterType", bound=Union[BodyParameter, "RequestBuilderBodyParameter"] -) +EntryBodyParameterType = TypeVar("EntryBodyParameterType", bound=Union[BodyParameter, "RequestBuilderBodyParameter"]) class Parameter(_ParameterBase): @@ -337,10 +308,7 @@ def __init__( @property def hide_in_operation_signature(self) -> bool: - if ( - self.code_model.options["version_tolerant"] - and self.client_name == "maxpagesize" - ): + if self.code_model.options["version_tolerant"] and self.client_name == "maxpagesize": return True return False @@ -382,10 +350,7 @@ def method_location( # pylint: disable=too-many-return-statements ParameterLocation.HEADER, ParameterLocation.QUERY, ) - if ( - self.code_model.options["only_path_and_body_params_positional"] - and query_or_header - ): + if self.code_model.options["only_path_and_body_params_positional"] and query_or_header: return ParameterMethodLocation.KEYWORD_ONLY return ParameterMethodLocation.POSITIONAL @@ -411,10 +376,7 @@ def method_location(self) -> ParameterMethodLocation: return ParameterMethodLocation.KWARG if ( self.is_host - and ( - self.code_model.options["version_tolerant"] - or self.code_model.options["low_level_client"] - ) + and (self.code_model.options["version_tolerant"] or self.code_model.options["low_level_client"]) and not self.code_model.options["azure_arm"] ): # this means i am the base url diff --git a/packages/autorest.python/autorest/codegen/models/parameter_list.py b/packages/autorest.python/autorest/codegen/models/parameter_list.py index 72d4db4cebb..73278584a34 100644 --- a/packages/autorest.python/autorest/codegen/models/parameter_list.py +++ b/packages/autorest.python/autorest/codegen/models/parameter_list.py @@ -33,12 +33,8 @@ ConfigParameter, ) -ParameterType = TypeVar( - "ParameterType", bound=Union[Parameter, RequestBuilderParameter] -) -BodyParameterType = TypeVar( - "BodyParameterType", bound=Union[BodyParameter, RequestBuilderBodyParameter] -) +ParameterType = TypeVar("ParameterType", bound=Union[Parameter, RequestBuilderParameter]) +BodyParameterType = TypeVar("BodyParameterType", bound=Union[BodyParameter, RequestBuilderBodyParameter]) if TYPE_CHECKING: from .code_model import CodeModel @@ -52,17 +48,13 @@ class ParameterImplementation(Enum): _LOGGER = logging.getLogger(__name__) -def method_signature_helper( - positional: List[str], keyword_only: Optional[List[str]], kwarg_params: List[str] -): +def method_signature_helper(positional: List[str], keyword_only: Optional[List[str]], kwarg_params: List[str]): keyword_only = keyword_only or [] return positional + keyword_only + kwarg_params def _sort(params): - return sorted( - params, key=lambda x: not (x.client_default_value or x.optional), reverse=True - ) + return sorted(params, key=lambda x: not (x.client_default_value or x.optional), reverse=True) class _ParameterListBase( @@ -110,17 +102,13 @@ def parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], ParameterType @staticmethod @abstractmethod - def body_parameter_creator() -> ( - Callable[[Dict[str, Any], "CodeModel"], BodyParameterType] - ): + def body_parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], BodyParameterType]: """Callable for creating body parameters""" @property def grouped(self) -> List[Union[ParameterType, BodyParameterType]]: """All parameters that are inside a parameter group""" - params: List[Union[ParameterType, BodyParameterType]] = [ - p for p in self.parameters if p.grouped_by - ] + params: List[Union[ParameterType, BodyParameterType]] = [p for p in self.parameters if p.grouped_by] if self.has_body and self.body_parameter.grouped_by: params.append(self.body_parameter) return params @@ -137,11 +125,7 @@ def has_body(self) -> bool: @property def path(self) -> List[ParameterType]: """All path parameters""" - return [ - p - for p in self.parameters - if p.location in (ParameterLocation.PATH, ParameterLocation.ENDPOINT_PATH) - ] + return [p for p in self.parameters if p.location in (ParameterLocation.PATH, ParameterLocation.ENDPOINT_PATH)] @property def query(self) -> List[ParameterType]: @@ -162,34 +146,20 @@ def constant(self) -> List[Union[ParameterType, BodyParameterType]]: def positional(self) -> List[Union[ParameterType, BodyParameterType]]: """All positional parameters""" return _sort( - [ - p - for p in self.unsorted_method_params - if p.method_location == ParameterMethodLocation.POSITIONAL - ] + [p for p in self.unsorted_method_params if p.method_location == ParameterMethodLocation.POSITIONAL] ) @property def keyword_only(self) -> List[Union[ParameterType, BodyParameterType]]: """All keyword only parameters""" return _sort( - [ - p - for p in self.unsorted_method_params - if p.method_location == ParameterMethodLocation.KEYWORD_ONLY - ] + [p for p in self.unsorted_method_params if p.method_location == ParameterMethodLocation.KEYWORD_ONLY] ) @property def kwarg(self) -> List[Union[ParameterType, BodyParameterType]]: """All kwargs""" - return _sort( - [ - p - for p in self.unsorted_method_params - if p.method_location == ParameterMethodLocation.KWARG - ] - ) + return _sort([p for p in self.unsorted_method_params if p.method_location == ParameterMethodLocation.KWARG]) @property def body_parameter(self) -> BodyParameterType: @@ -261,20 +231,12 @@ def kwargs_to_pop(self) -> List[Union[ParameterType, BodyParameterType]]: """Method kwargs we want to pop""" # don't want to pop bodies unless it's a constant kwargs_to_pop = self.kwarg - return [ - k - for k in kwargs_to_pop - if k.location != ParameterLocation.BODY or k.constant - ] + return [k for k in kwargs_to_pop if k.location != ParameterLocation.BODY or k.constant] @property def call(self) -> List[str]: """How to pass in parameters to call the operation""" - retval = [ - p.client_name - for p in self.method - if p.method_location == ParameterMethodLocation.POSITIONAL - ] + retval = [p.client_name for p in self.method if p.method_location == ParameterMethodLocation.POSITIONAL] retval.extend( [ f"{p.client_name}={p.client_name}" @@ -287,15 +249,10 @@ def call(self) -> List[str]: @classmethod def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel"): - parameters = [ - cls.parameter_creator()(parameter, code_model) - for parameter in yaml_data["parameters"] - ] + parameters = [cls.parameter_creator()(parameter, code_model) for parameter in yaml_data["parameters"]] body_parameter = None if yaml_data.get("bodyParameter"): - body_parameter = cls.body_parameter_creator()( - yaml_data["bodyParameter"], code_model - ) + body_parameter = cls.body_parameter_creator()(yaml_data["bodyParameter"], code_model) return cls( yaml_data, code_model, @@ -304,11 +261,7 @@ def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel"): ) -class _ParameterList( - _ParameterListBase[ # pylint: disable=unsubscriptable-object - Parameter, BodyParameter - ] -): +class _ParameterList(_ParameterListBase[Parameter, BodyParameter]): # pylint: disable=unsubscriptable-object """Base Parameter class for the two operation ParameterLists""" @staticmethod @@ -316,9 +269,7 @@ def parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], Parameter]: return Parameter.from_yaml @staticmethod - def body_parameter_creator() -> ( - Callable[[Dict[str, Any], "CodeModel"], BodyParameter] - ): + def body_parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], BodyParameter]: return BodyParameter.from_yaml @property @@ -327,9 +278,7 @@ def implementation(self) -> str: @property def path(self) -> List[Parameter]: - return [ - k for k in super().path if k.location == ParameterLocation.ENDPOINT_PATH - ] + return [k for k in super().path if k.location == ParameterLocation.ENDPOINT_PATH] class ParameterList(_ParameterList): @@ -337,22 +286,16 @@ class ParameterList(_ParameterList): class _RequestBuilderParameterList( - _ParameterListBase[ # pylint: disable=unsubscriptable-object - RequestBuilderParameter, RequestBuilderBodyParameter - ] + _ParameterListBase[RequestBuilderParameter, RequestBuilderBodyParameter] # pylint: disable=unsubscriptable-object ): """_RequestBuilderParameterList is base parameter list for RequestBuilder classes""" @staticmethod - def parameter_creator() -> ( - Callable[[Dict[str, Any], "CodeModel"], RequestBuilderParameter] - ): + def parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], RequestBuilderParameter]: return RequestBuilderParameter.from_yaml @staticmethod - def body_parameter_creator() -> ( - Callable[[Dict[str, Any], "CodeModel"], RequestBuilderBodyParameter] - ): + def body_parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], RequestBuilderBodyParameter]: return RequestBuilderBodyParameter.from_yaml @property @@ -367,34 +310,21 @@ def unsorted_method_params( retval = [ p for p in super().unsorted_method_params - if not ( - p.location == ParameterLocation.BODY - and cast(RequestBuilderBodyParameter, p).is_partial_body - ) + if not (p.location == ParameterLocation.BODY and cast(RequestBuilderBodyParameter, p).is_partial_body) ] - retval.extend( - [ - p - for p in self.parameters - if p.implementation == "Client" and p.in_method_signature - ] - ) + retval.extend([p for p in self.parameters if p.implementation == "Client" and p.in_method_signature]) return retval @property def path(self) -> List[RequestBuilderParameter]: - return [ - p for p in super().path if p.location != ParameterLocation.ENDPOINT_PATH - ] + return [p for p in super().path if p.location != ParameterLocation.ENDPOINT_PATH] @property def constant( self, ) -> List[Union[RequestBuilderParameter, RequestBuilderBodyParameter]]: """All constant parameters""" - return [ - p for p in super().constant if p.location != ParameterLocation.ENDPOINT_PATH - ] + return [p for p in super().constant if p.location != ParameterLocation.ENDPOINT_PATH] class RequestBuilderParameterList(_RequestBuilderParameterList): @@ -405,15 +335,11 @@ class OverloadedRequestBuilderParameterList(_RequestBuilderParameterList): """Parameter list for OverloadedRequestBuilder""" -class _ClientGlobalParameterList( # pylint: disable=abstract-method - _ParameterListBase[ParameterType, BodyParameter] -): +class _ClientGlobalParameterList(_ParameterListBase[ParameterType, BodyParameter]): # pylint: disable=abstract-method """Base parameter list for client and config classes""" @staticmethod - def body_parameter_creator() -> ( - Callable[[Dict[str, Any], "CodeModel"], BodyParameter] - ): + def body_parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], BodyParameter]: return BodyParameter.from_yaml @property @@ -429,9 +355,7 @@ def credential(self) -> Optional[ParameterType]: @property def path(self) -> List[ParameterType]: - return [ - p for p in super().path if p.location == ParameterLocation.ENDPOINT_PATH - ] + return [p for p in super().path if p.location == ParameterLocation.ENDPOINT_PATH] class ClientGlobalParameterList(_ClientGlobalParameterList[ClientParameter]): diff --git a/packages/autorest.python/autorest/codegen/models/primitive_types.py b/packages/autorest.python/autorest/codegen/models/primitive_types.py index 1200b2ca2c5..a4fc0392a6d 100644 --- a/packages/autorest.python/autorest/codegen/models/primitive_types.py +++ b/packages/autorest.python/autorest/codegen/models/primitive_types.py @@ -24,9 +24,7 @@ def __repr__(self) -> str: class PrimitiveType(BaseType): # pylint: disable=abstract-method - def description( - self, *, is_operation_file: bool # pylint: disable=unused-argument - ) -> str: + def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument return "" def type_annotation(self, **kwargs: Any) -> str: @@ -46,25 +44,18 @@ def get_json_template_representation( if optional: comment = add_to_description(comment, "Optional.") if self.client_default_value is not None: - client_default_value_declaration = ( - client_default_value_declaration - or self.get_declaration(self.client_default_value) + client_default_value_declaration = client_default_value_declaration or self.get_declaration( + self.client_default_value ) if client_default_value_declaration: - comment = add_to_description( - comment, f"Default value is {client_default_value_declaration}." - ) + comment = add_to_description(comment, f"Default value is {client_default_value_declaration}.") else: - client_default_value_declaration = ( - self.default_template_representation_declaration - ) + client_default_value_declaration = self.default_template_representation_declaration if description: comment = add_to_description(comment, description) if comment: comment = f"# {comment}" - return client_default_value_declaration + ( - "" if self.code_model.for_test else comment - ) + return client_default_value_declaration + ("" if self.code_model.for_test else comment) @property def default_template_representation_declaration(self) -> str: @@ -149,9 +140,7 @@ def default_template_representation_declaration(self) -> str: def imports(self, **kwargs: Any) -> FileImport: file_import = FileImport(self.code_model) - file_import.add_submodule_import( - "typing", self._iterator_name(**kwargs), ImportType.STDLIB - ) + file_import.add_submodule_import("typing", self._iterator_name(**kwargs), ImportType.STDLIB) return file_import @property @@ -176,16 +165,12 @@ def default_template_representation_declaration(self) -> str: def imports(self, **kwargs: Any) -> FileImport: file_import = FileImport(self.code_model) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, TypingSection.CONDITIONAL) return file_import @property def instance_check_template(self) -> str: - raise ValueError( - "Shouldn't do instance check on an anytype, it can be anything" - ) + raise ValueError("Shouldn't do instance check on an anytype, it can be anything") class AnyObjectType(PrimitiveType): @@ -230,26 +215,10 @@ def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None: @property def serialization_constraints(self) -> List[str]: validation_constraints = [ - ( - f"maximum_ex={self.maximum}" - if self.maximum is not None and self.exclusive_maximum - else None - ), - ( - f"maximum={self.maximum}" - if self.maximum is not None and not self.exclusive_maximum - else None - ), - ( - f"minimum_ex={self.minimum}" - if self.minimum is not None and self.exclusive_minimum - else None - ), - ( - f"minimum={self.minimum}" - if self.minimum is not None and not self.exclusive_minimum - else None - ), + (f"maximum_ex={self.maximum}" if self.maximum is not None and self.exclusive_maximum else None), + (f"maximum={self.maximum}" if self.maximum is not None and not self.exclusive_maximum else None), + (f"minimum_ex={self.minimum}" if self.minimum is not None and self.exclusive_minimum else None), + (f"minimum={self.minimum}" if self.minimum is not None and not self.exclusive_minimum else None), f"multiple={self.multiple}" if self.multiple else None, ] return [x for x in validation_constraints if x is not None] @@ -353,9 +322,7 @@ def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None: super().__init__(yaml_data=yaml_data, code_model=code_model) self.max_length: Optional[int] = yaml_data.get("maxLength") self.min_length: Optional[int] = ( - yaml_data.get("minLength", 0) - if yaml_data.get("maxLength") - else yaml_data.get("minLength") + yaml_data.get("minLength", 0) if yaml_data.get("maxLength") else yaml_data.get("minLength") ) self.pattern: Optional[str] = yaml_data.get("pattern") @@ -400,8 +367,7 @@ def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None: super().__init__(yaml_data=yaml_data, code_model=code_model) self.encode = ( "rfc3339" - if yaml_data.get("encode", "date-time") == "date-time" - or yaml_data.get("encode", "date-time") == "rfc3339" + if yaml_data.get("encode", "date-time") == "date-time" or yaml_data.get("encode", "date-time") == "rfc3339" else "rfc7231" ) diff --git a/packages/autorest.python/autorest/codegen/models/property.py b/packages/autorest.python/autorest/codegen/models/property.py index 3dad9cb0f48..bdda254c248 100644 --- a/packages/autorest.python/autorest/codegen/models/property.py +++ b/packages/autorest.python/autorest/codegen/models/property.py @@ -37,12 +37,8 @@ def __init__( if self.client_default_value is None: self.client_default_value = self.type.client_default_value self.flattened_names: List[str] = yaml_data.get("flattenedNames", []) - self.is_multipart_file_input: bool = yaml_data.get( - "isMultipartFileInput", False - ) - self.flatten = self.yaml_data.get("flatten", False) and not getattr( - self.type, "flattened_property", False - ) + self.is_multipart_file_input: bool = yaml_data.get("isMultipartFileInput", False) + self.flatten = self.yaml_data.get("flatten", False) and not getattr(self.type, "flattened_property", False) @property def pylint_disable(self) -> str: @@ -59,9 +55,7 @@ def description(self, *, is_operation_file: bool) -> str: description = add_to_description(description, "Required.") # don't want model type documentation as part of property doc type_description = ( - "" - if isinstance(self.type, ModelType) - else self.type.description(is_operation_file=is_operation_file) + "" if isinstance(self.type, ModelType) else self.type.description(is_operation_file=is_operation_file) ) return add_to_description(description, type_description) @@ -77,11 +71,7 @@ def client_default_value_declaration(self) -> str: def constant(self) -> bool: # this bool doesn't consider you to be constant if you are a discriminator # you also have to be required to be considered a constant - return ( - isinstance(self.type, ConstantType) - and not self.optional - and not self.is_discriminator - ) + return isinstance(self.type, ConstantType) and not self.optional and not self.is_discriminator @property def is_input(self): @@ -104,16 +94,10 @@ def is_base_discriminator(self) -> bool: """If this discriminator is on the base model for polymorphic inheritance""" if self.is_enum_discriminator: return self.is_polymorphic and self.client_default_value is None - return ( - self.is_discriminator - and self.is_polymorphic - and cast(ConstantType, self.type).value is None - ) + return self.is_discriminator and self.is_polymorphic and cast(ConstantType, self.type).value is None def type_annotation(self, *, is_operation_file: bool = False) -> str: - types_type_annotation = self.type.type_annotation( - is_operation_file=is_operation_file - ) + types_type_annotation = self.type.type_annotation(is_operation_file=is_operation_file) if self.is_multipart_file_input: # we only support FileType or list of FileType types_type_annotation = types_type_annotation.replace("bytes", "FileType") @@ -137,9 +121,7 @@ def get_json_template_representation( file_type_str = '"filetype"' if self.code_model.for_test else "filetype" return f"[{file_type_str}]" if self.type.type == "list" else file_type_str if self.client_default_value: - client_default_value_declaration = self.get_declaration( - self.client_default_value - ) + client_default_value_declaration = self.get_declaration(self.client_default_value) if self.description(is_operation_file=True): description = self.description(is_operation_file=True) # make sure there is no \n otherwise the json template will be invalid @@ -172,9 +154,7 @@ def imports(self, **kwargs) -> FileImport: file_import = FileImport(self.code_model) if self.is_discriminator and isinstance(self.type, EnumType): return file_import - file_import.merge( - self.type.imports(**kwargs, relative_path="..", model_typing=True) - ) + file_import.merge(self.type.imports(**kwargs, relative_path="..", model_typing=True)) if self.optional and self.client_default_value is None: file_import.add_submodule_import("typing", "Optional", ImportType.STDLIB) if self.code_model.options["models_mode"] == "dpg": diff --git a/packages/autorest.python/autorest/codegen/models/request_builder.py b/packages/autorest.python/autorest/codegen/models/request_builder.py index 817e4ef4e79..b8786adba6f 100644 --- a/packages/autorest.python/autorest/codegen/models/request_builder.py +++ b/packages/autorest.python/autorest/codegen/models/request_builder.py @@ -87,19 +87,12 @@ def response_docstring_type(self, **kwargs) -> str: def imports(self) -> FileImport: file_import = FileImport(self.code_model) relative_path = ".." - if ( - not self.code_model.options["builders_visibility"] == "embedded" - and self.group_name - ): + if not self.code_model.options["builders_visibility"] == "embedded" and self.group_name: relative_path = "..." if self.group_name else ".." if self.abstract: return file_import for parameter in self.parameters.method: - file_import.merge( - parameter.imports( - async_mode=False, relative_path=relative_path, operation=self - ) - ) + file_import.merge(parameter.imports(async_mode=False, relative_path=relative_path, operation=self)) file_import.add_submodule_import( "rest", @@ -113,33 +106,23 @@ def imports(self) -> FileImport: "case_insensitive_dict", ImportType.SDKCORE, ) - file_import.add_submodule_import( - "typing", "Any", ImportType.STDLIB, typing_section=TypingSection.CONDITIONAL - ) + file_import.add_submodule_import("typing", "Any", ImportType.STDLIB, typing_section=TypingSection.CONDITIONAL) file_import.add_msrest_import( relative_path=( "..." - if ( - not self.code_model.options["builders_visibility"] == "embedded" - and self.group_name - ) + if (not self.code_model.options["builders_visibility"] == "embedded" and self.group_name) else ".." ), msrest_import_type=MsrestImportType.Serializer, typing_section=TypingSection.REGULAR, ) - if ( - self.overloads - and self.code_model.options["builders_visibility"] != "embedded" - ): + if self.overloads and self.code_model.options["builders_visibility"] != "embedded": file_import.add_submodule_import("typing", "overload", ImportType.STDLIB) return file_import @staticmethod @abstractmethod - def parameter_list_type() -> ( - Callable[[Dict[str, Any], "CodeModel"], ParameterListType] - ): ... + def parameter_list_type() -> Callable[[Dict[str, Any], "CodeModel"], ParameterListType]: ... @classmethod def get_name( @@ -150,13 +133,8 @@ def get_name( client: "Client", ) -> str: additional_mark = "" - if ( - code_model.options["combine_operation_files"] - and code_model.options["builders_visibility"] == "embedded" - ): - additional_mark = ( - yaml_data["groupName"] or client.yaml_data["builderPadName"] - ) + if code_model.options["combine_operation_files"] and code_model.options["builders_visibility"] == "embedded": + additional_mark = yaml_data["groupName"] or client.yaml_data["builderPadName"] names = [ "build", additional_mark, @@ -193,19 +171,13 @@ def from_yaml( class RequestBuilder(RequestBuilderBase[RequestBuilderParameterList]): @staticmethod - def parameter_list_type() -> ( - Callable[[Dict[str, Any], "CodeModel"], RequestBuilderParameterList] - ): + def parameter_list_type() -> Callable[[Dict[str, Any], "CodeModel"], RequestBuilderParameterList]: return RequestBuilderParameterList.from_yaml -class OverloadedRequestBuilder( - RequestBuilderBase[OverloadedRequestBuilderParameterList] -): +class OverloadedRequestBuilder(RequestBuilderBase[OverloadedRequestBuilderParameterList]): @staticmethod - def parameter_list_type() -> ( - Callable[[Dict[str, Any], "CodeModel"], OverloadedRequestBuilderParameterList] - ): + def parameter_list_type() -> Callable[[Dict[str, Any], "CodeModel"], OverloadedRequestBuilderParameterList]: return OverloadedRequestBuilderParameterList.from_yaml diff --git a/packages/autorest.python/autorest/codegen/models/request_builder_parameter.py b/packages/autorest.python/autorest/codegen/models/request_builder_parameter.py index fb6488b7b57..9ed4e9e590b 100644 --- a/packages/autorest.python/autorest/codegen/models/request_builder_parameter.py +++ b/packages/autorest.python/autorest/codegen/models/request_builder_parameter.py @@ -40,9 +40,7 @@ def type_annotation(self, **kwargs: Any) -> str: @property def in_method_signature(self) -> bool: return ( - super().in_method_signature - and not self.is_partial_body - and self.code_model.options["models_mode"] != "dpg" + super().in_method_signature and not self.is_partial_body and self.code_model.options["models_mode"] != "dpg" ) @property @@ -54,9 +52,7 @@ def method_location(self) -> ParameterMethodLocation: ) @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "RequestBuilderBodyParameter": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "RequestBuilderBodyParameter": return super().from_yaml(yaml_data, code_model) # type: ignore @property @@ -92,9 +88,7 @@ def in_method_signature(self) -> bool: if self.grouped_by and not self.in_flattened_body: return True return super().in_method_signature and not ( - self.location == ParameterLocation.ENDPOINT_PATH - or self.in_flattened_body - or self.grouper + self.location == ParameterLocation.ENDPOINT_PATH or self.in_flattened_body or self.grouper ) @property @@ -106,10 +100,7 @@ def method_location(self) -> ParameterMethodLocation: super_method_location = super().method_location if super_method_location == ParameterMethodLocation.KWARG: return super_method_location - if ( - self.in_overriden - and super_method_location == ParameterMethodLocation.KEYWORD_ONLY - ): + if self.in_overriden and super_method_location == ParameterMethodLocation.KEYWORD_ONLY: return ParameterMethodLocation.KWARG if self.location != ParameterLocation.PATH: return ParameterMethodLocation.KEYWORD_ONLY diff --git a/packages/autorest.python/autorest/codegen/models/response.py b/packages/autorest.python/autorest/codegen/models/response.py index b275e8b1c91..bd78c440f12 100644 --- a/packages/autorest.python/autorest/codegen/models/response.py +++ b/packages/autorest.python/autorest/codegen/models/response.py @@ -34,9 +34,7 @@ def serialization_type(self) -> str: return self.type.serialization_type @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "ResponseHeader": + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "ResponseHeader": from . import build_type return cls( @@ -141,35 +139,21 @@ def _get_import_type(self, input_path: str) -> ImportType: # helper function to return imports for responses based off # of whether we're importing from the core library, or users # are customizing responses - return ( - ImportType.SDKCORE - if self.code_model.core_library.split(".")[0] in input_path - else ImportType.THIRDPARTY - ) + return ImportType.SDKCORE if self.code_model.core_library.split(".")[0] in input_path else ImportType.THIRDPARTY @classmethod - def from_yaml( - cls, yaml_data: Dict[str, Any], code_model: "CodeModel" - ) -> "Response": - type = ( - code_model.lookup_type(id(yaml_data["type"])) - if yaml_data.get("type") - else None - ) + def from_yaml(cls, yaml_data: Dict[str, Any], code_model: "CodeModel") -> "Response": + type = code_model.lookup_type(id(yaml_data["type"])) if yaml_data.get("type") else None # use ByteIteratorType if we are returning a binary type default_content_type = yaml_data.get("defaultContentType", "application/json") if isinstance(type, BinaryType) or ( - isinstance(type, ByteArraySchema) - and default_content_type != "application/json" + isinstance(type, ByteArraySchema) and default_content_type != "application/json" ): type = BinaryIteratorType(type.yaml_data, type.code_model) return cls( yaml_data=yaml_data, code_model=code_model, - headers=[ - ResponseHeader.from_yaml(header, code_model) - for header in yaml_data["headers"] - ], + headers=[ResponseHeader.from_yaml(header, code_model) for header in yaml_data["headers"]], type=type, ) @@ -181,13 +165,8 @@ class PagingResponse(Response): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.item_type = self.code_model.lookup_type(id(self.yaml_data["itemType"])) - self.pager_sync: str = ( - self.yaml_data.get("pagerSync") - or f"{self.code_model.core_library}.paging.ItemPaged" - ) - default_paging_submodule = ( - f"{'async_' if self.code_model.is_azure_flavor else ''}paging" - ) + self.pager_sync: str = self.yaml_data.get("pagerSync") or f"{self.code_model.core_library}.paging.ItemPaged" + default_paging_submodule = f"{'async_' if self.code_model.is_azure_flavor else ''}paging" self.pager_async: str = ( self.yaml_data.get("pagerAsync") or f"{self.code_model.core_library}.{default_paging_submodule}.AsyncItemPaged" @@ -227,9 +206,7 @@ def _imports_shared(self, **kwargs: Any) -> FileImport: pager = self.get_pager(async_mode) pager_path = self.get_pager_import_path(async_mode) - file_import.add_submodule_import( - pager_path, pager, self._get_import_type(pager_path) - ) + file_import.add_submodule_import(pager_path, pager, self._get_import_type(pager_path)) return file_import def imports(self, **kwargs: Any) -> FileImport: @@ -250,11 +227,7 @@ def imports_for_multiapi(self, **kwargs: Any) -> FileImport: class LROResponse(Response): def get_poller_path(self, async_mode: bool) -> str: - return ( - self.yaml_data["pollerAsync"] - if async_mode - else self.yaml_data["pollerSync"] - ) + return self.yaml_data["pollerAsync"] if async_mode else self.yaml_data["pollerSync"] def get_poller(self, async_mode: bool) -> str: """Get the name of the poller. Default is LROPoller / AsyncLROPoller""" @@ -262,11 +235,7 @@ def get_poller(self, async_mode: bool) -> str: def get_polling_method_path(self, async_mode: bool) -> str: """Get the full name of the poller path. Default are the azure core pollers""" - return ( - self.yaml_data["pollingMethodAsync"] - if async_mode - else self.yaml_data["pollingMethodSync"] - ) + return self.yaml_data["pollingMethodAsync"] if async_mode else self.yaml_data["pollingMethodSync"] def get_polling_method(self, async_mode: bool) -> str: """Get the default pollint method""" @@ -308,27 +277,21 @@ def _imports_shared(self, **kwargs: Any) -> FileImport: async_mode = kwargs["async_mode"] poller_import_path = ".".join(self.get_poller_path(async_mode).split(".")[:-1]) poller = self.get_poller(async_mode) - file_import.add_submodule_import( - poller_import_path, poller, self._get_import_type(poller_import_path) - ) + file_import.add_submodule_import(poller_import_path, poller, self._get_import_type(poller_import_path)) return file_import def imports(self, **kwargs: Any) -> FileImport: file_import = self._imports_shared(**kwargs) async_mode = kwargs["async_mode"] - default_polling_method_import_path = ".".join( - self.get_polling_method_path(async_mode).split(".")[:-1] - ) + default_polling_method_import_path = ".".join(self.get_polling_method_path(async_mode).split(".")[:-1]) default_polling_method = self.get_polling_method(async_mode) file_import.add_submodule_import( default_polling_method_import_path, default_polling_method, self._get_import_type(default_polling_method_import_path), ) - default_no_polling_method_import_path = ".".join( - self.get_no_polling_method_path(async_mode).split(".")[:-1] - ) + default_no_polling_method_import_path = ".".join(self.get_no_polling_method_path(async_mode).split(".")[:-1]) default_no_polling_method = self.get_no_polling_method(async_mode) file_import.add_submodule_import( default_no_polling_method_import_path, @@ -336,9 +299,7 @@ def imports(self, **kwargs: Any) -> FileImport: self._get_import_type(default_no_polling_method_import_path), ) - base_polling_method_import_path = ".".join( - self.get_base_polling_method_path(async_mode).split(".")[:-1] - ) + base_polling_method_import_path = ".".join(self.get_base_polling_method_path(async_mode).split(".")[:-1]) base_polling_method = self.get_base_polling_method(async_mode) file_import.add_submodule_import( base_polling_method_import_path, @@ -361,9 +322,7 @@ def docstring_type(self, **kwargs: Any) -> str: return f"~{self.get_poller_path(kwargs.get('async_mode', False))}[{paging_docstring_type}]" def docstring_text(self, **kwargs) -> str: - base_description = ( - "An instance of LROPoller that returns an iterator like instance of " - ) + base_description = "An instance of LROPoller that returns an iterator like instance of " if not self.code_model.options["version_tolerant"]: base_description += "either " return base_description + Response.docstring_text(self) diff --git a/packages/autorest.python/autorest/codegen/serializers/__init__.py b/packages/autorest.python/autorest/codegen/serializers/__init__.py index eeabab70fcb..377a6b20ad1 100644 --- a/packages/autorest.python/autorest/codegen/serializers/__init__.py +++ b/packages/autorest.python/autorest/codegen/serializers/__init__.py @@ -80,19 +80,13 @@ def __init__( @property def has_aio_folder(self) -> bool: - return not self.code_model.options["no_async"] and bool( - self.code_model.has_operations - ) + return not self.code_model.options["no_async"] and bool(self.code_model.has_operations) @property def has_operations_folder(self) -> bool: - return self.code_model.options["show_operations"] and bool( - self.code_model.has_operations - ) + return self.code_model.options["show_operations"] and bool(self.code_model.has_operations) - def _serialize_namespace_level( - self, env: Environment, namespace_path: Path, clients: List[Client] - ) -> None: + def _serialize_namespace_level(self, env: Environment, namespace_path: Path, clients: List[Client]) -> None: # if there was a patch file before, we keep it self._keep_patch_file(namespace_path / Path("_patch.py"), env) if self.has_aio_folder: @@ -100,28 +94,19 @@ def _serialize_namespace_level( if self.has_operations_folder: self._keep_patch_file( - namespace_path - / Path(self.code_model.operations_folder_name) - / Path("_patch.py"), + namespace_path / Path(self.code_model.operations_folder_name) / Path("_patch.py"), env, ) if self.has_aio_folder: self._keep_patch_file( - namespace_path - / Path("aio") - / Path(self.code_model.operations_folder_name) - / Path("_patch.py"), + namespace_path / Path("aio") / Path(self.code_model.operations_folder_name) / Path("_patch.py"), env, ) - self._serialize_and_write_top_level_folder( - env=env, namespace_path=namespace_path, clients=clients - ) + self._serialize_and_write_top_level_folder(env=env, namespace_path=namespace_path, clients=clients) if any(c for c in self.code_model.clients if c.operation_groups): if self.code_model.options["builders_visibility"] != "embedded": - self._serialize_and_write_rest_layer( - env=env, namespace_path=namespace_path - ) + self._serialize_and_write_rest_layer(env=env, namespace_path=namespace_path) if self.has_aio_folder: self._serialize_and_write_aio_top_level_folder( env=env, @@ -130,13 +115,9 @@ def _serialize_namespace_level( ) if self.has_operations_folder: - self._serialize_and_write_operations_folder( - clients, env=env, namespace_path=namespace_path - ) + self._serialize_and_write_operations_folder(clients, env=env, namespace_path=namespace_path) if self.code_model.options["multiapi"]: - self._serialize_and_write_metadata( - env=env, namespace_path=namespace_path - ) + self._serialize_and_write_metadata(env=env, namespace_path=namespace_path) if self.code_model.options["package_mode"]: self._serialize_and_write_package_files(namespace_path=namespace_path) @@ -166,15 +147,11 @@ def serialize(self) -> None: ) namespace_path = ( - Path(".") - if self.code_model.options["no_namespace_folders"] - else Path(*self._name_space().split(".")) + Path(".") if self.code_model.options["no_namespace_folders"] else Path(*self._name_space().split(".")) ) p = namespace_path.parent - general_serializer = GeneralSerializer( - code_model=self.code_model, env=env, async_mode=False - ) + general_serializer = GeneralSerializer(code_model=self.code_model, env=env, async_mode=False) while p != Path("."): # write pkgutil init file self.write_file( @@ -195,23 +172,13 @@ def serialize(self) -> None: clients, ) in self.code_model.subnamespace_to_clients.items(): subnamespace_path = namespace_path / Path(subnamespace) - self._serialize_namespace_level( - env, subnamespace_path, [c for c in clients if c.has_operations] - ) + self._serialize_namespace_level(env, subnamespace_path, [c for c in clients if c.has_operations]) - if self.code_model.options["models_mode"] and ( - self.code_model.model_types or self.code_model.enums - ): - self._keep_patch_file( - namespace_path / Path("models") / Path("_patch.py"), env - ) + if self.code_model.options["models_mode"] and (self.code_model.model_types or self.code_model.enums): + self._keep_patch_file(namespace_path / Path("models") / Path("_patch.py"), env) - if self.code_model.options["models_mode"] and ( - self.code_model.model_types or self.code_model.enums - ): - self._serialize_and_write_models_folder( - env=env, namespace_path=namespace_path - ) + if self.code_model.options["models_mode"] and (self.code_model.model_types or self.code_model.enums): + self._serialize_and_write_models_folder(env=env, namespace_path=namespace_path) if not self.code_model.options["models_mode"]: # keep models file if users ended up just writing a models file if self.read_file(namespace_path / Path("models.py")): @@ -229,18 +196,14 @@ def _serialize_and_write_package_files(self, namespace_path: Path) -> None: root_of_sdk = self._package_root_folder(namespace_path) if self.code_model.options["package_mode"] in VALID_PACKAGE_MODE: env = Environment( - loader=PackageLoader( - "autorest.codegen", "templates/packaging_templates" - ), + loader=PackageLoader("autorest.codegen", "templates/packaging_templates"), undefined=StrictUndefined, ) package_files = _PACKAGE_FILES elif Path(self.code_model.options["package_mode"]).exists(): env = Environment( - loader=FileSystemLoader( - str(Path(self.code_model.options["package_mode"])) - ), + loader=FileSystemLoader(str(Path(self.code_model.options["package_mode"]))), keep_trailing_newline=True, undefined=StrictUndefined, ) @@ -250,10 +213,7 @@ def _serialize_and_write_package_files(self, namespace_path: Path) -> None: serializer = GeneralSerializer(self.code_model, env, async_mode=False) params = self.code_model.options["packaging_files_config"] or {} for template_name in package_files: - if ( - not self.code_model.is_azure_flavor - and template_name == "dev_requirements.txt.jinja2" - ): + if not self.code_model.is_azure_flavor and template_name == "dev_requirements.txt.jinja2": continue file = template_name.replace(".jinja2", "") output_name = root_of_sdk / file @@ -272,16 +232,10 @@ def _keep_patch_file(self, path_file: Path, env: Environment): PatchSerializer(env=env, code_model=self.code_model).serialize(), ) - def _serialize_and_write_models_folder( - self, env: Environment, namespace_path: Path - ) -> None: + def _serialize_and_write_models_folder(self, env: Environment, namespace_path: Path) -> None: # Write the models folder models_path = namespace_path / Path("models") - serializer = ( - DpgModelSerializer - if self.code_model.options["models_mode"] == "dpg" - else MsrestModelSerializer - ) + serializer = DpgModelSerializer if self.code_model.options["models_mode"] == "dpg" else MsrestModelSerializer if self.code_model.model_types: self.write_file( models_path / Path(f"{self.code_model.models_filename}.py"), @@ -297,24 +251,15 @@ def _serialize_and_write_models_folder( ModelInitSerializer(code_model=self.code_model, env=env).serialize(), ) - def _serialize_and_write_rest_layer( - self, env: Environment, namespace_path: Path - ) -> None: + def _serialize_and_write_rest_layer(self, env: Environment, namespace_path: Path) -> None: rest_path = namespace_path / Path(self.code_model.rest_layer_name) - group_names = { - rb.group_name for c in self.code_model.clients for rb in c.request_builders - } + group_names = {rb.group_name for c in self.code_model.clients for rb in c.request_builders} for group_name in group_names: request_builders = [ - r - for c in self.code_model.clients - for r in c.request_builders - if r.group_name == group_name + r for c in self.code_model.clients for r in c.request_builders if r.group_name == group_name ] - self._serialize_and_write_single_rest_layer( - env, rest_path, request_builders - ) + self._serialize_and_write_single_rest_layer(env, rest_path, request_builders) if not "" in group_names: self.write_file( rest_path / Path("__init__.py"), @@ -366,9 +311,7 @@ def _serialize_and_write_operations_file( operation_group=operation_group, ) self.write_file( - namespace_path - / Path(self.code_model.operations_folder_name) - / Path(f"{filename}.py"), + namespace_path / Path(self.code_model.operations_folder_name) / Path(f"{filename}.py"), operation_group_serializer.serialize(), ) @@ -382,12 +325,7 @@ def _serialize_and_write_operations_file( operation_group=operation_group, ) self.write_file( - ( - namespace_path - / Path("aio") - / Path(self.code_model.operations_folder_name) - / Path(f"{filename}.py") - ), + (namespace_path / Path("aio") / Path(self.code_model.operations_folder_name) / Path(f"{filename}.py")), operation_group_async_serializer.serialize(), ) @@ -399,9 +337,7 @@ def _serialize_and_write_operations_folder( code_model=self.code_model, clients=clients, env=env, async_mode=False ) self.write_file( - namespace_path - / Path(self.code_model.operations_folder_name) - / Path("__init__.py"), + namespace_path / Path(self.code_model.operations_folder_name) / Path("__init__.py"), operations_init_serializer.serialize(), ) @@ -411,10 +347,7 @@ def _serialize_and_write_operations_folder( code_model=self.code_model, clients=clients, env=env, async_mode=True ) self.write_file( - namespace_path - / Path("aio") - / Path(self.code_model.operations_folder_name) - / Path("__init__.py"), + namespace_path / Path("aio") / Path(self.code_model.operations_folder_name) / Path("__init__.py"), operations_async_init_serializer.serialize(), ) @@ -425,9 +358,7 @@ def _serialize_and_write_operations_folder( clients=clients, ) else: - for operation_group in get_all_operation_groups_recursively( - self.code_model.clients - ): + for operation_group in get_all_operation_groups_recursively(self.code_model.clients): self._serialize_and_write_operations_file( env=env, namespace_path=namespace_path, @@ -468,9 +399,7 @@ def _serialize_client_and_config_files( clients: List[Client], ) -> None: if self.code_model.has_operations: - namespace_path = ( - namespace_path / Path("aio") if async_mode else namespace_path - ) + namespace_path = namespace_path / Path("aio") if async_mode else namespace_path self.write_file( namespace_path / Path(f"{self.code_model.client_filename}.py"), general_serializer.serialize_service_client_file(clients), @@ -483,9 +412,7 @@ def _serialize_client_and_config_files( def _serialize_and_write_top_level_folder( self, env: Environment, namespace_path: Path, clients: List[Client] ) -> None: - general_serializer = GeneralSerializer( - code_model=self.code_model, env=env, async_mode=False - ) + general_serializer = GeneralSerializer(code_model=self.code_model, env=env, async_mode=False) self.write_file( namespace_path / Path("__init__.py"), @@ -493,9 +420,7 @@ def _serialize_and_write_top_level_folder( ) # Write the service client - self._serialize_client_and_config_files( - namespace_path, general_serializer, async_mode=False, clients=clients - ) + self._serialize_client_and_config_files(namespace_path, general_serializer, async_mode=False, clients=clients) if self.code_model.need_vendored_code(async_mode=False): self.write_file( namespace_path / Path("_vendor.py"), @@ -507,10 +432,7 @@ def _serialize_and_write_top_level_folder( # write the empty py.typed file self.write_file(namespace_path / Path("py.typed"), "# Marker file for PEP 561.") - if ( - not self.code_model.options["client_side_validation"] - and not self.code_model.options["multiapi"] - ): + if not self.code_model.options["client_side_validation"] and not self.code_model.options["multiapi"]: self.write_file( namespace_path / Path("_serialization.py"), general_serializer.serialize_serialization_file(), @@ -521,12 +443,7 @@ def _serialize_and_write_top_level_folder( general_serializer.serialize_model_base_file(), ) - if any( - og - for client in self.code_model.clients - for og in client.operation_groups - if og.need_validation - ): + if any(og for client in self.code_model.clients for og in client.operation_groups if og.need_validation): self.write_file( namespace_path / Path("_validation.py"), general_serializer.serialize_validation_file(), @@ -544,9 +461,7 @@ def _serialize_and_write_top_level_folder( def _serialize_and_write_aio_top_level_folder( self, env: Environment, namespace_path: Path, clients: List[Client] ) -> None: - aio_general_serializer = GeneralSerializer( - code_model=self.code_model, env=env, async_mode=True - ) + aio_general_serializer = GeneralSerializer(code_model=self.code_model, env=env, async_mode=True) aio_path = namespace_path / Path("aio") @@ -566,22 +481,16 @@ def _serialize_and_write_aio_top_level_folder( aio_general_serializer.serialize_vendor_file(clients), ) - def _serialize_and_write_metadata( - self, env: Environment, namespace_path: Path - ) -> None: + def _serialize_and_write_metadata(self, env: Environment, namespace_path: Path) -> None: metadata_serializer = MetadataSerializer(self.code_model, env) - self.write_file( - namespace_path / Path("_metadata.json"), metadata_serializer.serialize() - ) + self.write_file(namespace_path / Path("_metadata.json"), metadata_serializer.serialize()) @property def _namespace_from_package_name(self) -> str: return get_namespace_from_package_name(self.code_model.options["package_name"]) def _name_space(self) -> str: - if self.code_model.namespace.count( - "." - ) >= self._namespace_from_package_name.count("."): + if self.code_model.namespace.count(".") >= self._namespace_from_package_name.count("."): return self.code_model.namespace return self._namespace_from_package_name @@ -592,15 +501,11 @@ def _package_root_folder(self, namespace_path: Path) -> Path: @property def _additional_folder(self) -> Path: - namespace_config = get_namespace_config( - self.code_model.namespace, self.code_model.options["multiapi"] - ) + namespace_config = get_namespace_config(self.code_model.namespace, self.code_model.options["multiapi"]) num_of_namespace = namespace_config.count(".") + 1 num_of_package_namespace = self._namespace_from_package_name.count(".") + 1 if num_of_namespace > num_of_package_namespace: - return Path( - "/".join(namespace_config.split(".")[num_of_package_namespace:]) - ) + return Path("/".join(namespace_config.split(".")[num_of_package_namespace:])) return Path("") def _serialize_and_write_sample(self, env: Environment, namespace_path: Path): @@ -610,8 +515,7 @@ def _serialize_and_write_sample(self, env: Environment, namespace_path: Path): for operation in op_group.operations: if ( self.code_model.options["multiapi"] - and operation.api_versions[0] - != self.code_model.options["default_api_version"] + and operation.api_versions[0] != self.code_model.options["default_api_version"] ): continue samples = operation.yaml_data["samples"] @@ -622,10 +526,7 @@ def _serialize_and_write_sample(self, env: Environment, namespace_path: Path): file_name = to_snake_case(extract_sample_name(file)) + ".py" try: self.write_file( - out_path - / self._additional_folder - / _sample_output_path(file) - / file_name, + out_path / self._additional_folder / _sample_output_path(file) / file_name, SampleSerializer( code_model=self.code_model, env=env, @@ -644,9 +545,7 @@ def _serialize_and_write_test(self, env: Environment, namespace_path: Path): self.code_model.for_test = True out_path = self._package_root_folder(namespace_path) / Path("generated_tests") general_serializer = TestGeneralSerializer(code_model=self.code_model, env=env) - self.write_file( - out_path / "conftest.py", general_serializer.serialize_conftest() - ) + self.write_file(out_path / "conftest.py", general_serializer.serialize_conftest()) for is_async in (True, False): async_suffix = "_async" if is_async else "" general_serializer.is_async = is_async @@ -657,15 +556,12 @@ def _serialize_and_write_test(self, env: Environment, namespace_path: Path): for client in self.code_model.clients: for og in client.operation_groups: - test_serializer = TestSerializer( - self.code_model, env, client=client, operation_group=og - ) + test_serializer = TestSerializer(self.code_model, env, client=client, operation_group=og) for is_async in (True, False): try: test_serializer.is_async = is_async self.write_file( - out_path - / f"{to_snake_case(test_serializer.test_class_name)}.py", + out_path / f"{to_snake_case(test_serializer.test_class_name)}.py", test_serializer.serialize_test(), ) except Exception as e: # pylint: disable=broad-except diff --git a/packages/autorest.python/autorest/codegen/serializers/builder_serializer.py b/packages/autorest.python/autorest/codegen/serializers/builder_serializer.py index 51ab7d61ece..42df4ae0ff9 100644 --- a/packages/autorest.python/autorest/codegen/serializers/builder_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/builder_serializer.py @@ -86,9 +86,7 @@ def _escape_str(input_str: str) -> str: def _get_polymorphic_subtype_template(polymorphic_subtype: ModelType) -> List[str]: retval: List[str] = [] retval.append("") - retval.append( - f'# JSON input template for discriminator value "{polymorphic_subtype.discriminator_value}":' - ) + retval.append(f'# JSON input template for discriminator value "{polymorphic_subtype.discriminator_value}":') subtype_template = utils.json_dumps_template( polymorphic_subtype.get_json_template_representation(), ) @@ -99,18 +97,14 @@ def _get_polymorphic_parent( if not polymorphic_subtype: return None try: - return next( - p for p in polymorphic_subtype.parents if p.discriminated_subtypes - ) + return next(p for p in polymorphic_subtype.parents if p.discriminated_subtypes) except StopIteration: return None polymorphic_parent = _get_polymorphic_parent(polymorphic_subtype) while _get_polymorphic_parent(polymorphic_parent): polymorphic_parent = _get_polymorphic_parent(polymorphic_parent) - retval.extend( - f"{cast(ModelType, polymorphic_parent).snake_case_name} = {subtype_template}".splitlines() - ) + retval.extend(f"{cast(ModelType, polymorphic_parent).snake_case_name} = {subtype_template}".splitlines()) return retval @@ -133,55 +127,37 @@ def _serialize_grouped_body(builder: BuilderType) -> List[str]: def _serialize_flattened_body(body_parameter: BodyParameter) -> List[str]: retval: List[str] = [] if not body_parameter.property_to_parameter_name: - raise ValueError( - "This method can't be called if the operation doesn't need parameter flattening" - ) + raise ValueError("This method can't be called if the operation doesn't need parameter flattening") parameter_string = ", ".join( f"{property_name}={parameter_name}" for property_name, parameter_name in body_parameter.property_to_parameter_name.items() ) model_type = cast(ModelType, body_parameter.type) - retval.append( - f"{body_parameter.client_name} = _models.{model_type.name}({parameter_string})" - ) + retval.append(f"{body_parameter.client_name} = _models.{model_type.name}({parameter_string})") return retval -def _serialize_json_model_body( - body_parameter: BodyParameter, parameters: List[ParameterType] -) -> List[str]: +def _serialize_json_model_body(body_parameter: BodyParameter, parameters: List[ParameterType]) -> List[str]: retval: List[str] = [] if not body_parameter.property_to_parameter_name: - raise ValueError( - "This method can't be called if the operation doesn't need parameter flattening" - ) + raise ValueError("This method can't be called if the operation doesn't need parameter flattening") retval.append(f"if {body_parameter.client_name} is _Unset:") for p in parameters: - if ( - p.client_default_value is None - and not p.optional - and p.default_to_unset_sentinel - ): + if p.client_default_value is None and not p.optional and p.default_to_unset_sentinel: retval.append(f" if {p.client_name} is _Unset:") - retval.append( - f" raise TypeError('missing required argument: {p.client_name}')" - ) + retval.append(f" raise TypeError('missing required argument: {p.client_name}')") parameter_string = ", \n".join( f'"{property_name}": {parameter_name}' for property_name, parameter_name in body_parameter.property_to_parameter_name.items() ) model_type = cast(ModelType, body_parameter.type) - if isinstance(model_type, CombinedType) and model_type.target_model_subtype( - (JSONModelType,) - ): + if isinstance(model_type, CombinedType) and model_type.target_model_subtype((JSONModelType,)): model_type = model_type.target_model_subtype((JSONModelType,)) retval.append(f" {body_parameter.client_name} = {{{parameter_string}}}") retval.append(f" {body_parameter.client_name} = {{") - retval.append( - f" k: v for k, v in {body_parameter.client_name}.items() if v is not None" - ) + retval.append(f" k: v for k, v in {body_parameter.client_name}.items() if v is not None") retval.append(" }") return retval @@ -286,27 +262,20 @@ def _method_signature(self, builder: BuilderType) -> str: def method_signature_and_response_type_annotation( self, builder: BuilderType, *, want_decorators: Optional[bool] = True ) -> str: - response_type_annotation = builder.response_type_annotation( - async_mode=self.async_mode - ) + response_type_annotation = builder.response_type_annotation(async_mode=self.async_mode) method_signature = self._method_signature(builder) decorators = self.decorators(builder) decorators_str = "" if decorators and want_decorators: decorators_str = "\n".join(decorators) + "\n" - return ( - decorators_str - + utils.method_signature_and_response_type_annotation_template( - method_signature=method_signature, - response_type_annotation=response_type_annotation, - ) + return decorators_str + utils.method_signature_and_response_type_annotation_template( + method_signature=method_signature, + response_type_annotation=response_type_annotation, ) def description_and_summary(self, builder: BuilderType) -> List[str]: description_list: List[str] = [] - description_list.append( - f"{builder.summary.strip() if builder.summary else builder.description.strip()}" - ) + description_list.append(f"{builder.summary.strip() if builder.summary else builder.description.strip()}") if builder.summary and builder.description: description_list.append("") description_list.append(builder.description.strip()) @@ -336,23 +305,17 @@ def param_description(self, builder: BuilderType) -> List[str]: ): continue description_list.extend( - f":{param.description_keyword} {param.client_name}: {param.description}".replace( - "\n", "\n " - ).split( + f":{param.description_keyword} {param.client_name}: {param.description}".replace("\n", "\n ").split( "\n" ) ) docstring_type = param.docstring_type( async_mode=self.async_mode, ) - description_list.append( - f":{param.docstring_type_keyword} {param.client_name}: {docstring_type}" - ) + description_list.append(f":{param.docstring_type_keyword} {param.client_name}: {docstring_type}") return description_list - def param_description_and_response_docstring( - self, builder: BuilderType - ) -> List[str]: + def param_description_and_response_docstring(self, builder: BuilderType) -> List[str]: if builder.abstract: return [] return self.param_description(builder) + self.response_docstring(builder) @@ -363,17 +326,12 @@ def _json_response_template_name(self) -> str: ... def _json_input_example_template(self, builder: BuilderType) -> List[str]: template: List[str] = [] - if ( - not builder.parameters.has_body - or builder.parameters.body_parameter.flattened - ): + if not builder.parameters.has_body or builder.parameters.body_parameter.flattened: # No input template if now body parameter return template body_param = builder.parameters.body_parameter - if not isinstance( - body_param.type, (ListType, DictionaryType, ModelType, CombinedType) - ): + if not isinstance(body_param.type, (ListType, DictionaryType, ModelType, CombinedType)): return template if ( @@ -387,9 +345,7 @@ def _json_input_example_template(self, builder: BuilderType) -> List[str]: json_type = body_param.type if isinstance(body_param.type, CombinedType): - target_model_type = body_param.type.target_model_subtype( - (JSONModelType, DPGModelType) - ) + target_model_type = body_param.type.target_model_subtype((JSONModelType, DPGModelType)) if target_model_type is None: return template json_type = target_model_type @@ -398,9 +354,7 @@ def _json_input_example_template(self, builder: BuilderType) -> List[str]: json_type.get_polymorphic_subtypes(polymorphic_subtypes) if polymorphic_subtypes: # we just assume one kind of polymorphic body for input - discriminator_name = cast( - Property, polymorphic_subtypes[0].discriminator - ).wire_name + discriminator_name = cast(Property, polymorphic_subtypes[0].discriminator).wire_name template.append( "# The input is polymorphic. The following are possible polymorphic " f'inputs based off discriminator "{discriminator_name}":' @@ -411,25 +365,17 @@ def _json_input_example_template(self, builder: BuilderType) -> List[str]: len(polymorphic_subtypes), ) ): - template.extend( - _get_polymorphic_subtype_template(polymorphic_subtypes[idx]) - ) + template.extend(_get_polymorphic_subtype_template(polymorphic_subtypes[idx])) template.append("") - template.append( - "# JSON input template you can fill out and use as your body input." - ) + template.append("# JSON input template you can fill out and use as your body input.") json_template = utils.json_dumps_template( json_type.get_json_template_representation(), ) - template.extend( - f"{builder.parameters.body_parameter.client_name} = {json_template}".splitlines() - ) + template.extend(f"{builder.parameters.body_parameter.client_name} = {json_template}".splitlines()) return template def serialize_path(self, builder: BuilderType) -> List[str]: - return self.parameter_serializer.serialize_path( - builder.parameters.path, self.serializer_name - ) + return self.parameter_serializer.serialize_path(builder.parameters.path, self.serializer_name) @property def pipeline_name(self) -> str: @@ -439,9 +385,7 @@ def pipeline_name(self) -> str: ############################## REQUEST BUILDERS ############################## -class RequestBuilderSerializer( - _BuilderBaseSerializer[RequestBuilderType] -): # pylint: disable=abstract-method +class RequestBuilderSerializer(_BuilderBaseSerializer[RequestBuilderType]): # pylint: disable=abstract-method def description_and_summary(self, builder: RequestBuilderType) -> List[str]: retval = super().description_and_summary(builder) retval += [ @@ -467,21 +411,11 @@ def _json_response_template_name(self) -> str: def declare_non_inputtable_constants(builder: RequestBuilderType) -> List[str]: def _get_value(param): if param.location in [ParameterLocation.HEADER, ParameterLocation.QUERY]: - kwarg_dict = ( - "headers" - if param.location == ParameterLocation.HEADER - else "params" - ) - return ( - f"_{kwarg_dict}.pop('{param.wire_name}', {param.get_declaration()})" - ) + kwarg_dict = "headers" if param.location == ParameterLocation.HEADER else "params" + return f"_{kwarg_dict}.pop('{param.wire_name}', {param.get_declaration()})" return f"{param.get_declaration()}" - return [ - f"{p.client_name} = {_get_value(p)}" - for p in builder.parameters.constant - if not p.in_method_signature - ] + return [f"{p.client_name} = {_get_value(p)}" for p in builder.parameters.constant if not p.in_method_signature] @property def _function_def(self) -> str: @@ -505,16 +439,8 @@ def pop_kwargs_from_signature(self, builder: RequestBuilderType) -> List[str]: return self.parameter_serializer.pop_kwargs_from_signature( builder.parameters.kwargs_to_pop, check_kwarg_dict=True, - pop_headers_kwarg=( - PopKwargType.CASE_INSENSITIVE - if bool(builder.parameters.headers) - else PopKwargType.NO - ), - pop_params_kwarg=( - PopKwargType.CASE_INSENSITIVE - if bool(builder.parameters.query) - else PopKwargType.NO - ), + pop_headers_kwarg=(PopKwargType.CASE_INSENSITIVE if bool(builder.parameters.headers) else PopKwargType.NO), + pop_params_kwarg=(PopKwargType.CASE_INSENSITIVE if bool(builder.parameters.query) else PopKwargType.NO), ) @staticmethod @@ -526,15 +452,9 @@ def create_http_request(builder: RequestBuilderType) -> List[str]: retval.append(" params=_params,") if builder.parameters.headers: retval.append(" headers=_headers,") - if ( - builder.parameters.has_body - and builder.parameters.body_parameter.in_method_signature - ): + if builder.parameters.has_body and builder.parameters.body_parameter.in_method_signature: body_param = builder.parameters.body_parameter - if ( - body_param.constant - or body_param.method_location != ParameterMethodLocation.KWARG - ): + if body_param.constant or body_param.method_location != ParameterMethodLocation.KWARG: # we only need to pass it through if it's not a kwarg or it's a popped kwarg retval.append( f" {builder.parameters.body_parameter.client_name}=" @@ -576,11 +496,7 @@ def serialize_query(self, builder: RequestBuilderType) -> List[str]: return retval def construct_url(self, builder: RequestBuilderType) -> str: - if any( - o - for o in ["low_level_client", "version_tolerant"] - if self.code_model.options.get(o) - ): + if any(o for o in ["low_level_client", "version_tolerant"] if self.code_model.options.get(o)): url_value = _escape_str(builder.url) else: url_value = f'kwargs.pop("template_url", {_escape_str(builder.url)})' @@ -590,9 +506,7 @@ def construct_url(self, builder: RequestBuilderType) -> str: ############################## NORMAL OPERATIONS ############################## -class _OperationSerializer( - _BuilderBaseSerializer[OperationType] -): # pylint: disable=abstract-method +class _OperationSerializer(_BuilderBaseSerializer[OperationType]): # pylint: disable=abstract-method def description_and_summary(self, builder: OperationType) -> List[str]: retval = super().description_and_summary(builder) if builder.deprecated: @@ -620,9 +534,7 @@ def example_template(self, builder: OperationType) -> List[str]: response.get_polymorphic_subtypes(polymorphic_subtypes) if polymorphic_subtypes: # we just assume one kind of polymorphic body for input - discriminator_name = cast( - Property, polymorphic_subtypes[0].discriminator - ).wire_name + discriminator_name = cast(Property, polymorphic_subtypes[0].discriminator).wire_name retval.append("") retval.append( "# The response is polymorphic. The following are possible polymorphic " @@ -634,9 +546,7 @@ def example_template(self, builder: OperationType) -> List[str]: len(polymorphic_subtypes), ) ): - retval.extend( - _get_polymorphic_subtype_template(polymorphic_subtypes[idx]) - ) + retval.extend(_get_polymorphic_subtype_template(polymorphic_subtypes[idx])) if _get_json_response_template_to_status_codes(builder): retval.append("") @@ -644,14 +554,8 @@ def example_template(self, builder: OperationType) -> List[str]: response_body, status_codes, ) in _get_json_response_template_to_status_codes(builder).items(): - retval.append( - "# response body for status code(s): {}".format( - ", ".join(status_codes) - ) - ) - retval.extend( - f"{self._json_response_template_name} == {response_body}".splitlines() - ) + retval.append("# response body for status code(s): {}".format(", ".join(status_codes))) + retval.extend(f"{self._json_response_template_name} == {response_body}".splitlines()) return retval def make_pipeline_call(self, builder: OperationType) -> List[str]: @@ -697,16 +601,12 @@ def pop_kwargs_from_signature(self, builder: OperationType) -> List[str]: check_kwarg_dict=True, pop_headers_kwarg=( PopKwargType.CASE_INSENSITIVE - if builder.has_kwargs_to_pop_with_default( - kwargs_to_pop, ParameterLocation.HEADER # type: ignore - ) + if builder.has_kwargs_to_pop_with_default(kwargs_to_pop, ParameterLocation.HEADER) # type: ignore else PopKwargType.SIMPLE ), pop_params_kwarg=( PopKwargType.CASE_INSENSITIVE - if builder.has_kwargs_to_pop_with_default( - kwargs_to_pop, ParameterLocation.QUERY # type: ignore - ) + if builder.has_kwargs_to_pop_with_default(kwargs_to_pop, ParameterLocation.QUERY) # type: ignore else PopKwargType.SIMPLE ), check_client_input=not self.code_model.options["multiapi"], @@ -719,18 +619,12 @@ def pop_kwargs_from_signature(self, builder: OperationType) -> List[str]: pylint_disable = "" if any(x.startswith("_") for x in cls_annotation.split(".")): pylint_disable = " # pylint: disable=protected-access" - kwargs.append( - f"cls: {cls_annotation} = kwargs.pop({pylint_disable}\n 'cls', None\n)" - ) + kwargs.append(f"cls: {cls_annotation} = kwargs.pop({pylint_disable}\n 'cls', None\n)") return kwargs def response_docstring(self, builder: OperationType) -> List[str]: - response_str = ( - f":return: {builder.response_docstring_text(async_mode=self.async_mode)}" - ) - rtype_str = ( - f":rtype: {builder.response_docstring_type(async_mode=self.async_mode)}" - ) + response_str = f":return: {builder.response_docstring_text(async_mode=self.async_mode)}" + rtype_str = f":rtype: {builder.response_docstring_type(async_mode=self.async_mode)}" return [ response_str, rtype_str, @@ -753,14 +647,8 @@ def _serialize_body_parameter(self, builder: OperationType) -> List[str]: else body_param.type ), ) - file_fields = [ - p.wire_name for p in model_type.properties if p.is_multipart_file_input - ] - data_fields = [ - p.wire_name - for p in model_type.properties - if not p.is_multipart_file_input - ] + file_fields = [p.wire_name for p in model_type.properties if p.is_multipart_file_input] + data_fields = [p.wire_name for p in model_type.properties if not p.is_multipart_file_input] retval.extend( [ "_body = (", @@ -777,19 +665,13 @@ def _serialize_body_parameter(self, builder: OperationType) -> List[str]: body_kwarg_name = builder.request_builder.parameters.body_parameter.client_name send_xml = builder.parameters.body_parameter.type.is_xml - xml_serialization_ctxt = ( - body_param.type.xml_serialization_ctxt if send_xml else None - ) + xml_serialization_ctxt = body_param.type.xml_serialization_ctxt if send_xml else None ser_ctxt_name = "serialization_ctxt" if xml_serialization_ctxt and self.code_model.options["models_mode"]: retval.append(f'{ser_ctxt_name} = {{"xml": {{{xml_serialization_ctxt}}}}}') if self.code_model.options["models_mode"] == "msrest": - is_xml_cmd = _xml_config( - send_xml, builder.parameters.body_parameter.content_types - ) - serialization_ctxt_cmd = ( - f", {ser_ctxt_name}={ser_ctxt_name}" if xml_serialization_ctxt else "" - ) + is_xml_cmd = _xml_config(send_xml, builder.parameters.body_parameter.content_types) + serialization_ctxt_cmd = f", {ser_ctxt_name}={ser_ctxt_name}" if xml_serialization_ctxt else "" create_body_call = ( f"_{body_kwarg_name} = self._serialize.body({body_param.client_name}, " f"'{body_param.type.serialization_type}'{is_xml_cmd}{serialization_ctxt_cmd})" @@ -832,17 +714,12 @@ def _create_body_parameter( body_kwarg_name = builder.request_builder.parameters.body_parameter.client_name body_param_type = body_param.type if isinstance(body_param_type, BinaryType) or ( - isinstance(body_param.type, ByteArraySchema) - and body_param.default_content_type != "application/json" + isinstance(body_param.type, ByteArraySchema) and body_param.default_content_type != "application/json" ): retval.append(f"_{body_kwarg_name} = {body_param.client_name}") if ( not body_param.default_content_type - and not next( - p - for p in builder.parameters - if p.wire_name.lower() == "content-type" - ).optional + and not next(p for p in builder.parameters if p.wire_name.lower() == "content-type").optional ): content_types = "'" + "', '".join(body_param.content_types) + "'" retval.extend( @@ -856,30 +733,17 @@ def _create_body_parameter( retval.extend(self._serialize_body_parameter(builder)) return retval - def _initialize_overloads( - self, builder: OperationType, is_paging: bool = False - ) -> List[str]: + def _initialize_overloads(self, builder: OperationType, is_paging: bool = False) -> List[str]: retval: List[str] = [] # For paging, we put body parameter in local place outside `prepare_request` if is_paging: return retval - same_content_type = ( - len( - set( - o.parameters.body_parameter.default_content_type - for o in builder.overloads - ) - ) - == 1 - ) + same_content_type = len(set(o.parameters.body_parameter.default_content_type for o in builder.overloads)) == 1 if same_content_type: - default_content_type = builder.overloads[ - 0 - ].parameters.body_parameter.default_content_type + default_content_type = builder.overloads[0].parameters.body_parameter.default_content_type retval.append(f'content_type = content_type or "{default_content_type}"') client_names = [ - overload.request_builder.parameters.body_parameter.client_name - for overload in builder.overloads + overload.request_builder.parameters.body_parameter.client_name for overload in builder.overloads ] for v in sorted(set(client_names), key=client_names.index): retval.append(f"_{v} = None") @@ -887,43 +751,20 @@ def _initialize_overloads( # if there is a binary overload, we do a binary check first. binary_overload = cast( OperationType, - next( - ( - o - for o in builder.overloads - if isinstance(o.parameters.body_parameter.type, BinaryType) - ) - ), + next((o for o in builder.overloads if isinstance(o.parameters.body_parameter.type, BinaryType))), ) binary_body_param = binary_overload.parameters.body_parameter - retval.append( - f"if {binary_body_param.type.instance_check_template.format(binary_body_param.client_name)}:" - ) + retval.append(f"if {binary_body_param.type.instance_check_template.format(binary_body_param.client_name)}:") if binary_body_param.default_content_type and not same_content_type: - retval.append( - f' content_type = content_type or "{binary_body_param.default_content_type}"' - ) - retval.extend( - f" {l}" for l in self._create_body_parameter(binary_overload) - ) + retval.append(f' content_type = content_type or "{binary_body_param.default_content_type}"') + retval.extend(f" {l}" for l in self._create_body_parameter(binary_overload)) retval.append("else:") other_overload = cast( OperationType, - next( - ( - o - for o in builder.overloads - if not isinstance(o.parameters.body_parameter.type, BinaryType) - ) - ), - ) - retval.extend( - f" {l}" for l in self._create_body_parameter(other_overload) + next((o for o in builder.overloads if not isinstance(o.parameters.body_parameter.type, BinaryType))), ) - if ( - other_overload.parameters.body_parameter.default_content_type - and not same_content_type - ): + retval.extend(f" {l}" for l in self._create_body_parameter(other_overload)) + if other_overload.parameters.body_parameter.default_content_type and not same_content_type: retval.append( " content_type = content_type or " f'"{other_overload.parameters.body_parameter.default_content_type}"' @@ -936,13 +777,8 @@ def _initialize_overloads( f"{if_statement} {body_param.type.instance_check_template.format(body_param.client_name)}:" ) if body_param.default_content_type and not same_content_type: - retval.append( - f' content_type = content_type or "{body_param.default_content_type}"' - ) - retval.extend( - f" {l}" - for l in self._create_body_parameter(cast(OperationType, overload)) - ) + retval.append(f' content_type = content_type or "{body_param.default_content_type}"') + retval.extend(f" {l}" for l in self._create_body_parameter(cast(OperationType, overload))) return retval def _create_request_builder_call( @@ -978,11 +814,7 @@ def _create_request_builder_call( type_ignore = ( parameter.grouped_by and parameter.client_default_value is not None - and next( - p - for p in builder.parameters - if p.grouper and p.client_name == parameter.grouped_by - ).optional + and next(p for p in builder.parameters if p.grouper and p.client_name == parameter.grouped_by).optional ) retval.append( f" {parameter.client_name}={parameter.name_in_high_level_operation}," @@ -998,38 +830,25 @@ def _create_request_builder_call( elif request_builder.overloads: seen_body_params = set() for overload in request_builder.overloads: - body_param = cast( - RequestBuilderBodyParameter, overload.parameters.body_parameter - ) + body_param = cast(RequestBuilderBodyParameter, overload.parameters.body_parameter) if body_param.client_name in seen_body_params: continue seen_body_params.add(body_param.client_name) - retval.append( - f" {body_param.client_name}={body_param.name_in_high_level_operation}," - ) + retval.append(f" {body_param.client_name}={body_param.name_in_high_level_operation},") elif request_builder.parameters.has_body: - body_param = cast( - RequestBuilderBodyParameter, request_builder.parameters.body_parameter - ) - retval.append( - f" {body_param.client_name}={body_param.name_in_high_level_operation}," - ) + body_param = cast(RequestBuilderBodyParameter, request_builder.parameters.body_parameter) + retval.append(f" {body_param.client_name}={body_param.name_in_high_level_operation},") retval.append(" headers=_headers,") retval.append(" params=_params,") retval.append(")") return retval - def _postprocess_http_request( - self, builder: OperationType, template_url: Optional[str] = None - ) -> List[str]: + def _postprocess_http_request(self, builder: OperationType, template_url: Optional[str] = None) -> List[str]: retval: List[str] = [] if not self.code_model.options["version_tolerant"]: pass_files = "" - if ( - builder.parameters.has_body - and builder.parameters.body_parameter.client_name == "files" - ): + if builder.parameters.has_body and builder.parameters.body_parameter.client_name == "files": pass_files = ", _files" retval.append(f"_request = _convert_request(_request{pass_files})") if builder.parameters.path: @@ -1061,11 +880,7 @@ def _call_request_builder_helper( # pylint: disable=too-many-statements # unflatten before passing to request builder as well retval.extend(_serialize_flattened_body(builder.parameters.body_parameter)) if is_json_model_type(builder.parameters): - retval.extend( - _serialize_json_model_body( - builder.parameters.body_parameter, builder.parameters.parameters - ) - ) + retval.extend(_serialize_json_model_body(builder.parameters.body_parameter, builder.parameters.parameters)) if builder.has_form_data_body: retval.extend(self._create_body_parameter(builder)) elif builder.overloads: @@ -1075,18 +890,12 @@ def _call_request_builder_helper( # pylint: disable=too-many-statements # non-overloaded body retval.extend(self._create_body_parameter(builder)) retval.append("") - retval.extend( - self._create_request_builder_call(builder, request_builder, is_next_request) - ) + retval.extend(self._create_request_builder_call(builder, request_builder, is_next_request)) retval.extend(self._postprocess_http_request(builder, template_url)) return retval - def call_request_builder( - self, builder: OperationType, is_paging: bool = False - ) -> List[str]: - return self._call_request_builder_helper( - builder, builder.request_builder, is_paging=is_paging - ) + def call_request_builder(self, builder: OperationType, is_paging: bool = False) -> List[str]: + return self._call_request_builder_helper(builder, builder.request_builder, is_paging=is_paging) def response_headers_and_deserialization( self, @@ -1112,9 +921,7 @@ def response_headers_and_deserialization( if self.code_model.options["version_tolerant"]: deserialized = "response.iter_bytes()" else: - deserialized = ( - f"response.stream_download(self._client.{self.pipeline_name})" - ) + deserialized = f"response.stream_download(self._client.{self.pipeline_name})" deserialize_code.append(f"deserialized = {deserialized}") elif response.type: pylint_disable = "" @@ -1122,9 +929,7 @@ def response_headers_and_deserialization( pylint_disable = " # pylint: disable=protected-access" if self.code_model.options["models_mode"] == "msrest": deserialize_code.append("deserialized = self._deserialize(") - deserialize_code.append( - f" '{response.serialization_type}',{pylint_disable}" - ) + deserialize_code.append(f" '{response.serialization_type}',{pylint_disable}") deserialize_code.append(" pipeline_response") deserialize_code.append(")") elif self.code_model.options["models_mode"] == "dpg": @@ -1137,26 +942,16 @@ def response_headers_and_deserialization( and response.default_content_type == "application/json" else "" ) - response_attr = ( - "json" - if _json_serializable(str(response.default_content_type)) - else "text" - ) + response_attr = "json" if _json_serializable(str(response.default_content_type)) else "text" deserialize_code.append("deserialized = _deserialize(") deserialize_code.append( f" {response.type.type_annotation(is_operation_file=True)},{pylint_disable}" ) - deserialize_code.append( - f" response.{response_attr}(){response.result_property}{format_filed}" - ) + deserialize_code.append(f" response.{response_attr}(){response.result_property}{format_filed}") deserialize_code.append(")") else: - deserialized_value = ( - "ET.fromstring(response.text())" - if response.type.is_xml - else "response.json()" - ) + deserialized_value = "ET.fromstring(response.text())" if response.type.is_xml else "response.json()" deserialize_code.append("if response.content:") deserialize_code.append(f" deserialized = {deserialized_value}") deserialize_code.append("else:") @@ -1173,9 +968,7 @@ def response_headers_and_deserialization( def handle_error_response(self, builder: OperationType) -> List[str]: async_await = "await " if self.async_mode else "" - retval = [ - f"if response.status_code not in {str(builder.success_status_codes)}:" - ] + retval = [f"if response.status_code not in {str(builder.success_status_codes)}:"] if not self.code_model.need_request_converter: retval.extend( [ @@ -1188,14 +981,9 @@ def handle_error_response(self, builder: OperationType) -> List[str]: f" map_error(status_code=response.status_code, response=response, error_map=error_map){type_ignore}" ) error_model = "" - if ( - builder.default_error_deserialization - and self.code_model.options["models_mode"] - ): + if builder.default_error_deserialization and self.code_model.options["models_mode"]: if self.code_model.options["models_mode"] == "dpg": - retval.append( - f" error = _deserialize({builder.default_error_deserialization}, response.json())" - ) + retval.append(f" error = _deserialize({builder.default_error_deserialization}, response.json())") else: retval.append( f" error = self._deserialize.failsafe_deserialize({builder.default_error_deserialization}, " @@ -1205,11 +993,7 @@ def handle_error_response(self, builder: OperationType) -> List[str]: retval.append( " raise HttpResponseError(response=response{}{})".format( error_model, - ( - ", error_format=ARMErrorFormat" - if self.code_model.options["azure_arm"] - else "" - ), + (", error_format=ARMErrorFormat" if self.code_model.options["azure_arm"] else ""), ) ) return retval @@ -1230,20 +1014,11 @@ def handle_response(self, builder: OperationType) -> List[str]: if response.headers or response.type: retval.append(f"if response.status_code == {status_code}:") retval.extend( - [ - f" {line}" - for line in self.response_headers_and_deserialization( - builder, response - ) - ] + [f" {line}" for line in self.response_headers_and_deserialization(builder, response)] ) retval.append("") else: - retval.extend( - self.response_headers_and_deserialization( - builder, builder.responses[0] - ) - ) + retval.extend(self.response_headers_and_deserialization(builder, builder.responses[0])) retval.append("") if builder.has_optional_return_type or self.code_model.options["models_mode"]: deserialized = "deserialized" @@ -1258,15 +1033,11 @@ def handle_response(self, builder: OperationType) -> List[str]: ) ) if builder.has_response_body and any( - response.is_stream_response or response.type - for response in builder.responses + response.is_stream_response or response.type for response in builder.responses ): retval.append("") retval.append(f"return {deserialized} # type: ignore") - if ( - builder.request_builder.method == "HEAD" - and self.code_model.options["head_as_boolean"] - ): + if builder.request_builder.method == "HEAD" and self.code_model.options["head_as_boolean"]: retval.append("return 200 <= response.status_code <= 299") return retval @@ -1286,16 +1057,11 @@ def error_map(self, builder: OperationType) -> List[str]: if isinstance(excep.type, ModelType): if self.code_model.options["models_mode"] == "msrest": error_model_str = ( - f", model=self._deserialize(" - f"_models.{excep.type.serialization_type}, response)" + f", model=self._deserialize(" f"_models.{excep.type.serialization_type}, response)" ) elif self.code_model.options["models_mode"] == "dpg": error_model_str = f", model=_deserialize(_models.{excep.type.name}, response.json())" - error_format_str = ( - ", error_format=ARMErrorFormat" - if self.code_model.options["azure_arm"] - else "" - ) + error_format_str = ", error_format=ARMErrorFormat" if self.code_model.options["azure_arm"] else "" for status_code in excep.status_codes: if status_code == 401: retval.append( @@ -1359,14 +1125,10 @@ class OperationSerializer(_OperationSerializer[Operation]): ... ############################## PAGING OPERATIONS ############################## -PagingOperationType = TypeVar( - "PagingOperationType", bound=Union[PagingOperation, LROPagingOperation] -) +PagingOperationType = TypeVar("PagingOperationType", bound=Union[PagingOperation, LROPagingOperation]) -class _PagingOperationSerializer( - _OperationSerializer[PagingOperationType] -): # pylint: disable=abstract-method +class _PagingOperationSerializer(_OperationSerializer[PagingOperationType]): # pylint: disable=abstract-method def __init__(self, code_model: CodeModel, async_mode: bool) -> None: # for pylint reasons need to redefine init # probably because inheritance is going too deep @@ -1376,9 +1138,7 @@ def __init__(self, code_model: CodeModel, async_mode: bool) -> None: self.parameter_serializer = ParameterSerializer() def serialize_path(self, builder: PagingOperationType) -> List[str]: - return self.parameter_serializer.serialize_path( - builder.parameters.path, self.serializer_name - ) + return self.parameter_serializer.serialize_path(builder.parameters.path, self.serializer_name) def decorators(self, builder: PagingOperationType) -> List[str]: """Decorators for the method""" @@ -1412,9 +1172,7 @@ def call_next_link_request_builder(self, builder: PagingOperationType) -> List[s next_link_str = "next_link" try: api_version_param = next( - p - for p in builder.client.parameters - if p.is_api_version and p.location == ParameterLocation.QUERY + p for p in builder.client.parameters if p.is_api_version and p.location == ParameterLocation.QUERY ) retval.append("# make call to next link with the client's api-version") retval.append("_parsed_next_link = urllib.parse.urlparse(next_link)") @@ -1446,17 +1204,10 @@ def _prepare_request_callback(self, builder: PagingOperationType) -> List[str]: retval = self._initialize_overloads(builder) retval.append("def prepare_request(next_link=None):") retval.append(" if not next_link:") - retval.extend( - [ - f" {line}" - for line in self.call_request_builder(builder, is_paging=True) - ] - ) + retval.extend([f" {line}" for line in self.call_request_builder(builder, is_paging=True)]) retval.append("") retval.append(" else:") - retval.extend( - [f" {line}" for line in self.call_next_link_request_builder(builder)] - ) + retval.extend([f" {line}" for line in self.call_next_link_request_builder(builder)]) if not builder.next_request_builder and self.code_model.is_legacy: retval.append(' _request.method = "GET"') else: @@ -1469,9 +1220,7 @@ def _function_def(self) -> str: return "def" def _extract_data_callback(self, builder: PagingOperationType) -> List[str]: - retval = [ - f"{'async ' if self.async_mode else ''}def extract_data(pipeline_response):" - ] + retval = [f"{'async ' if self.async_mode else ''}def extract_data(pipeline_response):"] response = builder.responses[0] deserialized = "pipeline_response.http_response.json()" if self.code_model.options["models_mode"] == "msrest": @@ -1488,17 +1237,11 @@ def _extract_data_callback(self, builder: PagingOperationType) -> List[str]: else: retval.append(f" deserialized = {deserialized}") item_name = builder.item_name - access = ( - f".{item_name}" - if self.code_model.options["models_mode"] == "msrest" - else f'["{item_name}"]' - ) + access = f".{item_name}" if self.code_model.options["models_mode"] == "msrest" else f'["{item_name}"]' list_of_elem_deserialized = "" if self.code_model.options["models_mode"] == "dpg": item_type = builder.item_type.type_annotation(is_operation_file=True) - list_of_elem_deserialized = ( - f"_deserialize({item_type}, deserialized{access})" - ) + list_of_elem_deserialized = f"_deserialize({item_type}, deserialized{access})" else: list_of_elem_deserialized = f"deserialized{access}" retval.append(f" list_of_elem = {list_of_elem_deserialized}") @@ -1511,9 +1254,7 @@ def _extract_data_callback(self, builder: PagingOperationType) -> List[str]: elif self.code_model.options["models_mode"] == "msrest": cont_token_property = f"deserialized.{continuation_token_name} or None" else: - cont_token_property = ( - f'deserialized.get("{continuation_token_name}") or None' - ) + cont_token_property = f'deserialized.get("{continuation_token_name}") or None' list_type = "AsyncList" if self.async_mode else "iter" retval.append(f" return {cont_token_property}, {list_type}(list_of_elem)") return retval @@ -1546,9 +1287,7 @@ class PagingOperationSerializer(_PagingOperationSerializer[PagingOperation]): .. ############################## LRO OPERATIONS ############################## -LROOperationType = TypeVar( - "LROOperationType", bound=Union[LROOperation, LROPagingOperation] -) +LROOperationType = TypeVar("LROOperationType", bound=Union[LROOperation, LROPagingOperation]) class _LROOperationSerializer(_OperationSerializer[LROOperationType]): @@ -1561,9 +1300,7 @@ def __init__(self, code_model: CodeModel, async_mode: bool) -> None: self.parameter_serializer = ParameterSerializer() def serialize_path(self, builder: LROOperationType) -> List[str]: - return self.parameter_serializer.serialize_path( - builder.parameters.path, self.serializer_name - ) + return self.parameter_serializer.serialize_path(builder.parameters.path, self.serializer_name) def initial_call(self, builder: LROOperationType) -> List[str]: retval = [ @@ -1573,19 +1310,14 @@ def initial_call(self, builder: LROOperationType) -> List[str]: retval.append(" 'polling_interval',") retval.append(" self._config.polling_interval") retval.append(")") - retval.append( - "cont_token: Optional[str] = kwargs.pop('continuation_token', None)" - ) + retval.append("cont_token: Optional[str] = kwargs.pop('continuation_token', None)") retval.append("if cont_token is None:") retval.append( f" raw_result = {self._call_method}self.{builder.initial_operation.name}(" f"{'' if any(rsp.type for rsp in builder.initial_operation.responses) else ' # type: ignore'}" ) retval.extend( - [ - f" {parameter.client_name}={parameter.client_name}," - for parameter in builder.parameters.method - ] + [f" {parameter.client_name}={parameter.client_name}," for parameter in builder.parameters.method] ) retval.append(" cls=lambda x,y,z: x,") retval.append(" headers=_headers,") @@ -1598,9 +1330,7 @@ def initial_call(self, builder: LROOperationType) -> List[str]: def return_lro_poller(self, builder: LROOperationType) -> List[str]: retval = [] lro_options_str = ( - "lro_options={'final-state-via': '" - + builder.lro_options["final-state-via"] - + "'}," + "lro_options={'final-state-via': '" + builder.lro_options["final-state-via"] + "'}," if builder.lro_options else "" ) @@ -1628,20 +1358,14 @@ def return_lro_poller(self, builder: LROOperationType) -> List[str]: ) retval.append("else: polling_method = polling") retval.append("if cont_token:") - retval.append( - f" return {builder.get_poller_with_response_type(self.async_mode)}.from_continuation_token(" - ) + retval.append(f" return {builder.get_poller_with_response_type(self.async_mode)}.from_continuation_token(") retval.append(" polling_method=polling_method,") retval.append(" continuation_token=cont_token,") retval.append(" client=self._client,") retval.append(" deserialization_callback=get_long_running_output") retval.append(" )") - retval.append( - f"return {builder.get_poller_with_response_type(self.async_mode)}(" - ) - retval.append( - " self._client, raw_result, get_long_running_output, polling_method # type: ignore" - ) + retval.append(f"return {builder.get_poller_with_response_type(self.async_mode)}(") + retval.append(" self._client, raw_result, get_long_running_output, polling_method # type: ignore") retval.append(" )") return retval @@ -1660,26 +1384,13 @@ def get_long_running_output(self, builder: LROOperationType) -> List[str]: ): retval.append(" response = pipeline_response.http_response") retval.extend( - [ - f" {line}" - for line in self.response_headers_and_deserialization( - builder, builder.lro_response - ) - ] + [f" {line}" for line in self.response_headers_and_deserialization(builder, builder.lro_response)] ) retval.append(" if cls:") retval.append( " return cls(pipeline_response, {}, {}){}".format( - ( - "deserialized" - if builder.lro_response and builder.lro_response.type - else "None" - ), - ( - "response_headers" - if builder.lro_response and builder.lro_response.headers - else "{}" - ), + ("deserialized" if builder.lro_response and builder.lro_response.type else "None"), + ("response_headers" if builder.lro_response and builder.lro_response.headers else "{}"), " # type: ignore", ) ) diff --git a/packages/autorest.python/autorest/codegen/serializers/client_serializer.py b/packages/autorest.python/autorest/codegen/serializers/client_serializer.py index 8b62dc37aa9..ce8dfd87964 100644 --- a/packages/autorest.python/autorest/codegen/serializers/client_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/client_serializer.py @@ -19,9 +19,7 @@ def __init__(self, client: Client) -> None: def _init_signature(self, async_mode: bool) -> str: pylint_disable = "" if not self.client.parameters.credential: - pylint_disable = ( - " # pylint: disable=missing-client-constructor-parameter-credential" - ) + pylint_disable = " # pylint: disable=missing-client-constructor-parameter-credential" return self.parameter_serializer.serialize_method( function_def="def", method_name="__init__", @@ -61,14 +59,10 @@ def property_descriptions(self, async_mode: bool) -> List[str]: operations_folder = ".aio.operations." if async_mode else ".operations." for og in [og for og in self.client.operation_groups if not og.is_mixin]: retval.append(f":ivar {og.property_name}: {og.class_name} operations") - property_type = ( - f"{self.client.code_model.namespace}{operations_folder}{og.class_name}" - ) + property_type = f"{self.client.code_model.namespace}{operations_folder}{og.class_name}" retval.append(f":vartype {og.property_name}: {property_type}") for param in self.client.parameters.method: - retval.append( - f":{param.description_keyword} {param.client_name}: {param.description}" - ) + retval.append(f":{param.description_keyword} {param.client_name}: {param.description}") retval.append( f":{param.docstring_type_keyword} {param.client_name}: {param.docstring_type(async_mode=async_mode)}" ) @@ -102,26 +96,18 @@ def host_variable_name(self) -> str: @property def should_init_super(self) -> bool: - return any( - og - for og in self.client.operation_groups - if og.is_mixin and og.has_abstract_operations - ) + return any(og for og in self.client.operation_groups if og.is_mixin and og.has_abstract_operations) def initialize_pipeline_client(self, async_mode: bool) -> List[str]: result = [] pipeline_client_name = self.client.pipeline_class(async_mode) - endpoint_name = ( - "base_url" if self.client.code_model.is_azure_flavor else "endpoint" - ) + endpoint_name = "base_url" if self.client.code_model.is_azure_flavor else "endpoint" params = { endpoint_name: self.host_variable_name, "policies": "_policies", } if not self.client.code_model.is_legacy and self.client.request_id_header_name: - result.append( - f'kwargs["request_id_header_name"] = "{self.client.request_id_header_name}"' - ) + result.append(f'kwargs["request_id_header_name"] = "{self.client.request_id_header_name}"') policies = build_policies( self.client.code_model.options["azure_arm"], async_mode, @@ -152,33 +138,23 @@ def _get_client_models_value(models_dict_name: str) -> str: add_private_models = len(self.client.code_model.model_types) != len( self.client.code_model.public_model_types ) - model_dict_name = ( - f"_models.{self.client.code_model.models_filename}" - if add_private_models - else "_models" - ) + model_dict_name = f"_models.{self.client.code_model.models_filename}" if add_private_models else "_models" retval.append( f"client_models{': Dict[str, Any]' if not self.client.code_model.model_types else ''}" f" = {_get_client_models_value(model_dict_name)}" ) if add_private_models and self.client.code_model.model_types: - update_dict = ( - "{k: v for k, v in _models.__dict__.items() if isinstance(v, type)}" - ) + update_dict = "{k: v for k, v in _models.__dict__.items() if isinstance(v, type)}" retval.append(f"client_models.update({update_dict})") client_models_str = "client_models" if is_msrest_model else "" retval.append(f"self._serialize = Serializer({client_models_str})") retval.append(f"self._deserialize = Deserializer({client_models_str})") if not self.client.code_model.options["client_side_validation"]: retval.append("self._serialize.client_side_validation = False") - operation_groups = [ - og for og in self.client.operation_groups if not og.is_mixin - ] + operation_groups = [og for og in self.client.operation_groups if not og.is_mixin] for og in operation_groups: if og.code_model.options["multiapi"]: - api_version = ( - f", '{og.api_versions[0]}'" if og.api_versions else ", None" - ) + api_version = f", '{og.api_versions[0]}'" if og.api_versions else ", None" else: api_version = "" retval.extend( @@ -201,22 +177,16 @@ def _send_request_signature(self) -> str: method_param_signatures=send_request_signature, ) - def send_request_signature_and_response_type_annotation( - self, async_mode: bool - ) -> str: + def send_request_signature_and_response_type_annotation(self, async_mode: bool) -> str: send_request_signature = self._send_request_signature() return utils.method_signature_and_response_type_annotation_template( method_signature=send_request_signature, - response_type_annotation=( - "Awaitable[AsyncHttpResponse]" if async_mode else "HttpResponse" - ), + response_type_annotation=("Awaitable[AsyncHttpResponse]" if async_mode else "HttpResponse"), ) def _example_make_call(self, async_mode: bool) -> List[str]: http_response = "AsyncHttpResponse" if async_mode else "HttpResponse" - retval = [ - f">>> response = {'await ' if async_mode else ''}client.{self.client.send_request_name}(request)" - ] + retval = [f">>> response = {'await ' if async_mode else ''}client.{self.client.send_request_name}(request)"] retval.append(f"<{http_response}: 200 OK>") return retval @@ -225,36 +195,26 @@ def _request_builder_example(self, async_mode: bool) -> List[str]: "We have helper methods to create requests specific to this service in " + f"`{self.client.code_model.namespace}.{self.client.code_model.rest_layer_name}`." ] - retval.append( - "Use these helper methods to create the request you pass to this method." - ) + retval.append("Use these helper methods to create the request you pass to this method.") retval.append("") request_builder = self.client.request_builders[0] request_builder_signature = ", ".join(request_builder.parameters.call) if request_builder.group_name: rest_imported = request_builder.group_name - request_builder_name = ( - f"{request_builder.group_name}.{request_builder.name}" - ) + request_builder_name = f"{request_builder.group_name}.{request_builder.name}" else: rest_imported = request_builder.name request_builder_name = request_builder.name full_path = f"{self.client.code_model.namespace}.{self.client.code_model.rest_layer_name}" retval.append(f">>> from {full_path} import {rest_imported}") - retval.append( - f">>> request = {request_builder_name}({request_builder_signature})" - ) - retval.append( - f"" - ) + retval.append(f">>> request = {request_builder_name}({request_builder_signature})") + retval.append(f"") retval.extend(self._example_make_call(async_mode)) return retval def _rest_request_example(self, async_mode: bool) -> List[str]: - retval = [ - f">>> from {self.client.code_model.core_library}.rest import HttpRequest" - ] + retval = [f">>> from {self.client.code_model.core_library}.rest import HttpRequest"] retval.append('>>> request = HttpRequest("GET", "https://www.example.org/")') retval.append("") retval.extend(self._example_make_call(async_mode)) @@ -269,27 +229,19 @@ def send_request_description(self, async_mode: bool) -> List[str]: else: retval.extend(self._rest_request_example(async_mode)) retval.append("") - retval.append( - "For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request" - ) + retval.append("For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request") retval.append("") retval.append(":param request: The network request you want to make. Required.") retval.append(f":type request: ~{rest_library}.HttpRequest") - retval.append( - ":keyword bool stream: Whether the response payload will be streamed. Defaults to False." - ) - retval.append( - ":return: The response of your network call. Does not do error handling on your response." - ) + retval.append(":keyword bool stream: Whether the response payload will be streamed. Defaults to False.") + retval.append(":return: The response of your network call. Does not do error handling on your response.") http_response = "AsyncHttpResponse" if async_mode else "HttpResponse" retval.append(f":rtype: ~{rest_library}.{http_response}") retval.append('"""') return retval def serialize_path(self) -> List[str]: - return self.parameter_serializer.serialize_path( - self.client.parameters.path, "self._serialize" - ) + return self.parameter_serializer.serialize_path(self.client.parameters.path, "self._serialize") class ConfigSerializer: @@ -302,9 +254,7 @@ def _init_signature(self, async_mode: bool) -> str: function_def="def", method_name="__init__", need_self_param=True, - method_param_signatures=self.client.config.parameters.method_signature( - async_mode - ), + method_param_signatures=self.client.config.parameters.method_signature(async_mode), ) def init_signature_and_response_type_annotation(self, async_mode: bool) -> str: @@ -331,8 +281,7 @@ def set_constants(self) -> List[str]: def check_required_parameters(self) -> List[str]: return [ - f"if {p.client_name} is None:\n" - f" raise ValueError(\"Parameter '{p.client_name}' must not be None.\")" + f"if {p.client_name} is None:\n" f" raise ValueError(\"Parameter '{p.client_name}' must not be None.\")" for p in self.client.config.parameters.method if not (p.optional or p.constant) ] @@ -341,8 +290,6 @@ def property_descriptions(self, async_mode: bool) -> List[str]: retval: List[str] = [] for p in self.client.config.parameters.method: retval.append(f":{p.description_keyword} {p.client_name}: {p.description}") - retval.append( - f":{p.docstring_type_keyword} {p.client_name}: {p.docstring_type(async_mode=async_mode)}" - ) + retval.append(f":{p.docstring_type_keyword} {p.client_name}: {p.docstring_type(async_mode=async_mode)}") retval.append('"""') return retval diff --git a/packages/autorest.python/autorest/codegen/serializers/enum_serializer.py b/packages/autorest.python/autorest/codegen/serializers/enum_serializer.py index df566d1e075..4b9ce87e3fc 100644 --- a/packages/autorest.python/autorest/codegen/serializers/enum_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/enum_serializer.py @@ -12,6 +12,4 @@ class EnumSerializer(BaseSerializer): def serialize(self) -> str: # Generate the enum file template = self.env.get_template("enum_container.py.jinja2") - return template.render( - code_model=self.code_model, file_import=FileImport(self.code_model) - ) + return template.render(code_model=self.code_model, file_import=FileImport(self.code_model)) diff --git a/packages/autorest.python/autorest/codegen/serializers/general_serializer.py b/packages/autorest.python/autorest/codegen/serializers/general_serializer.py index 8493860c819..f70f00a38f0 100644 --- a/packages/autorest.python/autorest/codegen/serializers/general_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/general_serializer.py @@ -35,9 +35,7 @@ def serialize_package_file(self, template_name: str, **kwargs: Any) -> str: template = self.env.get_template(template_name) package_parts = (self.code_model.options["package_name"] or "").split("-")[:-1] token_credential = any( - c - for c in self.code_model.clients - if isinstance(getattr(c.credential, "type", None), TokenCredentialType) + c for c in self.code_model.clients if isinstance(getattr(c.credential, "type", None), TokenCredentialType) ) version = self.code_model.options["package_version"] if any(x in version for x in ["a", "b", "rc"]) or version[0] == "0": @@ -48,13 +46,8 @@ def serialize_package_file(self, template_name: str, **kwargs: Any) -> str: "code_model": self.code_model, "dev_status": dev_status, "token_credential": token_credential, - "pkgutil_names": [ - ".".join(package_parts[: i + 1]) for i in range(len(package_parts)) - ], - "init_names": [ - "/".join(package_parts[: i + 1]) + "/__init__.py" - for i in range(len(package_parts)) - ], + "pkgutil_names": [".".join(package_parts[: i + 1]) for i in range(len(package_parts))], + "init_names": ["/".join(package_parts[: i + 1]) + "/__init__.py" for i in range(len(package_parts))], "client_name": self.code_model.clients[0].name, "namespace": self.code_model.namespace, } @@ -131,11 +124,7 @@ def serialize_vendor_file(self, clients: List[Client]) -> str: "MatchConditions", ImportType.SDKCORE, ) - if ( - self.code_model.has_form_data - and self.code_model.options["models_mode"] == "dpg" - and not self.async_mode - ): + if self.code_model.has_form_data and self.code_model.options["models_mode"] == "dpg" and not self.async_mode: file_import.add_submodule_import("typing", "IO", ImportType.STDLIB) file_import.add_submodule_import("typing", "Tuple", ImportType.STDLIB) file_import.add_submodule_import("typing", "Union", ImportType.STDLIB) @@ -191,9 +180,7 @@ def serialize_serialization_file(self) -> str: def serialize_model_base_file(self) -> str: template = self.env.get_template("model_base.py.jinja2") - return template.render( - code_model=self.code_model, file_import=FileImport(self.code_model) - ) + return template.render(code_model=self.code_model, file_import=FileImport(self.code_model)) def serialize_validation_file(self) -> str: template = self.env.get_template("validation.py.jinja2") @@ -214,11 +201,7 @@ def serialize_cross_language_definition_file(self) -> str: { ( f"{self.code_model.namespace}.{client.name}." - + ( - "" - if operation_group.is_mixin - else f"{operation_group.property_name}." - ) + + ("" if operation_group.is_mixin else f"{operation_group.property_name}.") + f"{operation.name}" ): operation.cross_language_definition_id for client in self.code_model.clients diff --git a/packages/autorest.python/autorest/codegen/serializers/import_serializer.py b/packages/autorest.python/autorest/codegen/serializers/import_serializer.py index 6d3bca4b2ca..2824a1e6750 100644 --- a/packages/autorest.python/autorest/codegen/serializers/import_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/import_serializer.py @@ -17,15 +17,12 @@ def _serialize_package(imports: List[ImportModel], delimiter: str) -> str: buffer = [] if any(i for i in imports if i.submodule_name is None): - buffer.append( - f"import {imports[0].module_name}{f' as {imports[0].alias}' if imports[0].alias else ''}" - ) + buffer.append(f"import {imports[0].module_name}{f' as {imports[0].alias}' if imports[0].alias else ''}") else: import_str = ", ".join( sorted( set( - f"{i.submodule_name} as {i.alias}" if i.alias else i.submodule_name # type: ignore - for i in imports + f"{i.submodule_name} as {i.alias}" if i.alias else i.submodule_name for i in imports # type: ignore ) ) ) @@ -38,9 +35,7 @@ def _serialize_versioned_package(i: ImportModel, delimiter: str) -> str: return "" buffer = [] for n, (version, module_name, comment) in enumerate(i.version_modules): - buffer.append( - "{} sys.version_info >= {}:".format("if" if n == 0 else "elif", version) - ) + buffer.append("{} sys.version_info >= {}:".format("if" if n == 0 else "elif", version)) buffer.append( f" from {module_name} import {i.submodule_name}{f' as {i.alias}' if i.alias else ''}" f"{f' # {comment}' if comment else ''}" @@ -57,12 +52,8 @@ def _serialize_import_type(imports: List[ImportModel], delimiter: str) -> str: """Serialize a given import type.""" import_list = [] for module_name in sorted(set(i.module_name for i in imports)): - normal_imports = [ - i for i in imports if i.module_name == module_name and not i.version_modules - ] - versioned_imports = [ - i for i in imports if i.module_name == module_name and i.version_modules - ] + normal_imports = [i for i in imports if i.module_name == module_name and not i.version_modules] + versioned_imports = [i for i in imports if i.module_name == module_name and i.version_modules] if normal_imports: import_list.append(_serialize_package(normal_imports, delimiter)) for i in versioned_imports: @@ -75,9 +66,7 @@ def _get_import_clauses(imports: List[ImportModel], delimiter: str) -> List[str] for import_type in ImportType: imports_with_import_type = [i for i in imports if i.import_type == import_type] if imports_with_import_type: - import_clause.append( - _serialize_import_type(imports_with_import_type, delimiter) - ) + import_clause.append(_serialize_import_type(imports_with_import_type, delimiter)) return import_clause @@ -86,15 +75,11 @@ def __init__(self, file_import: FileImport, async_mode: bool = False) -> None: self.file_import = file_import self.async_mode = async_mode - def _get_imports_list( - self, baseline_typing_section: TypingSection, add_conditional_typing: bool - ): + def _get_imports_list(self, baseline_typing_section: TypingSection, add_conditional_typing: bool): # If this is a python 3 file, our regular imports include the CONDITIONAL category # If this is not a python 3 file, our typing imports include the CONDITIONAL category file_import_copy = deepcopy(self.file_import) - if add_conditional_typing and any( - self.file_import.get_imports_from_section(TypingSection.CONDITIONAL) - ): + if add_conditional_typing and any(self.file_import.get_imports_from_section(TypingSection.CONDITIONAL)): # we switch the TypingSection key for the CONDITIONAL typing imports so we can merge # the imports together for i in file_import_copy.imports: @@ -104,20 +89,12 @@ def _get_imports_list( def _add_type_checking_import(self): if any(self.file_import.get_imports_from_section(TypingSection.TYPING)): - self.file_import.add_submodule_import( - "typing", "TYPE_CHECKING", ImportType.STDLIB - ) + self.file_import.add_submodule_import("typing", "TYPE_CHECKING", ImportType.STDLIB) def get_typing_definitions(self) -> str: - def declare_definition( - type_name: str, type_definition: TypeDefinition - ) -> List[str]: + def declare_definition(type_name: str, type_definition: TypeDefinition) -> List[str]: ret: List[str] = [] - definition_value = ( - type_definition.async_definition - if self.async_mode - else type_definition.sync_definition - ) + definition_value = type_definition.async_definition if self.async_mode else type_definition.sync_definition ret.append("{} = {}".format(type_name, definition_value)) return ret @@ -137,9 +114,7 @@ def __str__(self) -> str: ) if regular_imports_list: - regular_imports = "\n\n".join( - _get_import_clauses(regular_imports_list, "\n") - ) + regular_imports = "\n\n".join(_get_import_clauses(regular_imports_list, "\n")) typing_imports = "" typing_imports_list = self._get_imports_list( @@ -148,7 +123,5 @@ def __str__(self) -> str: ) if typing_imports_list: typing_imports += "\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n " - typing_imports += "\n\n ".join( - _get_import_clauses(typing_imports_list, "\n ") - ) + typing_imports += "\n\n ".join(_get_import_clauses(typing_imports_list, "\n ")) return regular_imports + typing_imports + self.get_typing_definitions() diff --git a/packages/autorest.python/autorest/codegen/serializers/metadata_serializer.py b/packages/autorest.python/autorest/codegen/serializers/metadata_serializer.py index ee5931686a3..35d374983fc 100644 --- a/packages/autorest.python/autorest/codegen/serializers/metadata_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/metadata_serializer.py @@ -87,9 +87,7 @@ def _mixin_imports( sync_mixin_imports = mixin_operation_group.imports_for_multiapi(async_mode=False) async_mixin_imports = mixin_operation_group.imports_for_multiapi(async_mode=True) - return _json_serialize_imports( - sync_mixin_imports.to_dict() - ), _json_serialize_imports(async_mixin_imports.to_dict()) + return _json_serialize_imports(sync_mixin_imports.to_dict()), _json_serialize_imports(async_mixin_imports.to_dict()) def _mixin_typing_definitions( @@ -100,12 +98,8 @@ def _mixin_typing_definitions( sync_mixin_imports = mixin_operation_group.imports_for_multiapi(async_mode=False) async_mixin_imports = mixin_operation_group.imports_for_multiapi(async_mode=True) - sync_mixin_typing_definitions = FileImportSerializer( - sync_mixin_imports, False - ).get_typing_definitions() - async_mixin_typing_definitions = FileImportSerializer( - async_mixin_imports, True - ).get_typing_definitions() + sync_mixin_typing_definitions = FileImportSerializer(sync_mixin_imports, False).get_typing_definitions() + async_mixin_typing_definitions = FileImportSerializer(async_mixin_imports, True).get_typing_definitions() return sync_mixin_typing_definitions, async_mixin_typing_definitions @@ -127,9 +121,7 @@ def _choose_api_version(self) -> Tuple[str, List[str]]: total_api_version_list.sort() # switching ' to " so json can decode the dict we end up writing to file - total_api_version_list = [ - str(api_version).replace("'", '"') for api_version in total_api_version_list - ] + total_api_version_list = [str(api_version).replace("'", '"') for api_version in total_api_version_list] if len(total_api_version_list) == 1: chosen_version = total_api_version_list[0] elif len(total_api_version_list) > 1: @@ -156,9 +148,7 @@ def _is_paging(operation): ), None, ) - mixin_operations = ( - mixin_operation_group.operations if mixin_operation_group else [] - ) + mixin_operations = mixin_operation_group.operations if mixin_operation_group else [] sync_mixin_imports, async_mixin_imports = _mixin_imports(mixin_operation_group) ( sync_mixin_typing_definitions, @@ -186,12 +176,8 @@ def _is_paging(operation): async_mixin_imports=async_mixin_imports, sync_mixin_typing_definitions=sync_mixin_typing_definitions, async_mixin_typing_definitions=async_mixin_typing_definitions, - sync_client_imports=_json_serialize_imports( - self.client.imports_for_multiapi(async_mode=False).to_dict() - ), - async_client_imports=_json_serialize_imports( - self.client.imports_for_multiapi(async_mode=True).to_dict() - ), + sync_client_imports=_json_serialize_imports(self.client.imports_for_multiapi(async_mode=False).to_dict()), + async_client_imports=_json_serialize_imports(self.client.imports_for_multiapi(async_mode=True).to_dict()), sync_config_imports=_json_serialize_imports( self.client.config.imports_for_multiapi(async_mode=False).to_dict() ), diff --git a/packages/autorest.python/autorest/codegen/serializers/model_init_serializer.py b/packages/autorest.python/autorest/codegen/serializers/model_init_serializer.py index ac395b52ed7..5df688adbb8 100644 --- a/packages/autorest.python/autorest/codegen/serializers/model_init_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/model_init_serializer.py @@ -15,11 +15,7 @@ def __init__(self, code_model: CodeModel, env: Environment) -> None: def serialize(self) -> str: schemas = [s.name for s in self.code_model.public_model_types] schemas.sort() - enums = ( - [e.name for e in self.code_model.enums if not e.internal] - if self.code_model.enums - else None - ) + enums = [e.name for e in self.code_model.enums if not e.internal] if self.code_model.enums else None if enums: enums.sort() diff --git a/packages/autorest.python/autorest/codegen/serializers/model_serializer.py b/packages/autorest.python/autorest/codegen/serializers/model_serializer.py index a237bb8aa95..b42d35e9709 100644 --- a/packages/autorest.python/autorest/codegen/serializers/model_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/model_serializer.py @@ -12,16 +12,12 @@ from .base_serializer import BaseSerializer -def _documentation_string( - prop: Property, description_keyword: str, docstring_type_keyword: str -) -> List[str]: +def _documentation_string(prop: Property, description_keyword: str, docstring_type_keyword: str) -> List[str]: retval: List[str] = [] sphinx_prefix = f":{description_keyword} {prop.client_name}:" description = prop.description(is_operation_file=False).replace("\\", "\\\\") retval.append(f"{sphinx_prefix} {description}" if description else sphinx_prefix) - retval.append( - f":{docstring_type_keyword} {prop.client_name}: {prop.type.docstring_type()}" - ) + retval.append(f":{docstring_type_keyword} {prop.client_name}: {prop.type.docstring_type()}") return retval @@ -60,9 +56,7 @@ def super_call(self, model: ModelType) -> List[str]: @staticmethod def initialize_discriminator_property(model: ModelType, prop: Property) -> str: - discriminator_value = ( - f"'{model.discriminator_value}'" if model.discriminator_value else None - ) + discriminator_value = f"'{model.discriminator_value}'" if model.discriminator_value else None if not discriminator_value: typing = "Optional[str]" else: @@ -87,11 +81,7 @@ def discriminator_docstring(model: ModelType) -> str: @staticmethod def _init_line_parameters(model: ModelType): - return [ - p - for p in model.properties - if not p.readonly and not p.is_discriminator and not p.constant - ] + return [p for p in model.properties if not p.readonly and not p.is_discriminator and not p.constant] def init_line(self, model: ModelType) -> List[str]: init_properties_declaration = [] @@ -109,15 +99,8 @@ def properties_to_pass_to_super(model: ModelType) -> str: properties_to_pass_to_super = [] for parent in model.parents: for prop in model.properties: - if ( - prop in parent.properties - and not prop.is_discriminator - and not prop.constant - and not prop.readonly - ): - properties_to_pass_to_super.append( - f"{prop.client_name}={prop.client_name}" - ) + if prop in parent.properties and not prop.is_discriminator and not prop.constant and not prop.readonly: + properties_to_pass_to_super.append(f"{prop.client_name}={prop.client_name}") properties_to_pass_to_super.append("**kwargs") return ", ".join(properties_to_pass_to_super) @@ -176,9 +159,7 @@ def initialize_properties(self, model: ModelType) -> List[str]: @staticmethod def declare_property(prop: Property) -> str: if prop.flattened_names: - attribute_key = ".".join( - _ModelSerializer.escape_dot(n) for n in prop.flattened_names - ) + attribute_key = ".".join(_ModelSerializer.escape_dot(n) for n in prop.flattened_names) else: attribute_key = _ModelSerializer.escape_dot(prop.wire_name) if prop.type.xml_serialization_ctxt: @@ -219,9 +200,7 @@ def imports(self) -> FileImport: if model.is_polymorphic: file_import.add_submodule_import("typing", "Dict", ImportType.STDLIB) if not model.internal and self.init_line(model): - file_import.add_submodule_import( - "typing", "overload", ImportType.STDLIB - ) + file_import.add_submodule_import("typing", "overload", ImportType.STDLIB) file_import.add_submodule_import("typing", "Mapping", ImportType.STDLIB) file_import.add_submodule_import("typing", "Any", ImportType.STDLIB) return file_import @@ -271,11 +250,7 @@ def declare_property(prop: Property) -> str: args.append(f'format="{prop.type.encode}"') # type: ignore field = "rest_discriminator" if prop.is_discriminator else "rest_field" - type_ignore = ( - prop.is_discriminator - and isinstance(prop.type, (ConstantType, EnumValue)) - and prop.type.value - ) + type_ignore = prop.is_discriminator and isinstance(prop.type, (ConstantType, EnumValue)) and prop.type.value return ( f"{prop.client_name}: {prop.type_annotation()} =" f' {field}({", ".join(args)}){" # type: ignore" if type_ignore else ""}' @@ -285,10 +260,7 @@ def initialize_properties(self, model: ModelType) -> List[str]: init_args = [] for prop in self.get_properties_to_declare(model): if prop.constant and not prop.is_base_discriminator: - init_args.append( - f"self.{prop.client_name}: {prop.type_annotation()} = " - f"{prop.get_declaration()}" - ) + init_args.append(f"self.{prop.client_name}: {prop.type_annotation()} = " f"{prop.get_declaration()}") return init_args @staticmethod @@ -296,10 +268,7 @@ def _init_line_parameters(model: ModelType): return [ p for p in model.properties - if p.is_base_discriminator - or not p.is_discriminator - and not p.constant - and p.visibility != ["read"] + if p.is_base_discriminator or not p.is_discriminator and not p.constant and p.visibility != ["read"] ] @staticmethod @@ -308,18 +277,11 @@ def properties_to_pass_to_super(model: ModelType) -> str: for parent in model.parents: for prop in model.properties: if ( - prop.client_name - in [ - prop.client_name - for prop in parent.properties - if prop.is_base_discriminator - ] + prop.client_name in [prop.client_name for prop in parent.properties if prop.is_base_discriminator] and prop.is_discriminator and not prop.constant and not prop.readonly ): - properties_to_pass_to_super.append( - f"{prop.client_name}={prop.get_declaration()}" - ) + properties_to_pass_to_super.append(f"{prop.client_name}={prop.get_declaration()}") properties_to_pass_to_super.append("**kwargs") return ", ".join(properties_to_pass_to_super) diff --git a/packages/autorest.python/autorest/codegen/serializers/operation_groups_serializer.py b/packages/autorest.python/autorest/codegen/serializers/operation_groups_serializer.py index 816253e17f2..4c04efbcd2e 100644 --- a/packages/autorest.python/autorest/codegen/serializers/operation_groups_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/operation_groups_serializer.py @@ -66,9 +66,7 @@ def serialize(self) -> str: ) ) - template = self.env.get_or_select_template( - "operation_groups_container.py.jinja2" - ) + template = self.env.get_or_select_template("operation_groups_container.py.jinja2") return template.render( code_model=self.code_model, diff --git a/packages/autorest.python/autorest/codegen/serializers/operations_init_serializer.py b/packages/autorest.python/autorest/codegen/serializers/operations_init_serializer.py index 30f598f392e..83966ffa899 100644 --- a/packages/autorest.python/autorest/codegen/serializers/operations_init_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/operations_init_serializer.py @@ -25,11 +25,7 @@ def __init__( def operation_group_imports(self) -> List[str]: def _get_filename(operation_group: OperationGroup) -> str: - return ( - "_operations" - if self.code_model.options["combine_operation_files"] - else operation_group.filename - ) + return "_operations" if self.code_model.options["combine_operation_files"] else operation_group.filename return [ f"from .{_get_filename(og)} import {og.class_name}" @@ -38,9 +34,7 @@ def _get_filename(operation_group: OperationGroup) -> str: ] def serialize(self) -> str: - operation_group_init_template = self.env.get_template( - "operations_folder_init.py.jinja2" - ) + operation_group_init_template = self.env.get_template("operations_folder_init.py.jinja2") return operation_group_init_template.render( code_model=self.code_model, diff --git a/packages/autorest.python/autorest/codegen/serializers/parameter_serializer.py b/packages/autorest.python/autorest/codegen/serializers/parameter_serializer.py index 0305eac60d7..8a41c850a7d 100644 --- a/packages/autorest.python/autorest/codegen/serializers/parameter_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/parameter_serializer.py @@ -121,9 +121,7 @@ def serialize_path( [ ' "{}": {},'.format( path_parameter.wire_name, - ParameterSerializer.serialize_parameter( - path_parameter, serializer_name - ), + ParameterSerializer.serialize_parameter(path_parameter, serializer_name), ) for path_parameter in parameters ] @@ -172,9 +170,7 @@ def pop_kwargs_from_signature( def append_pop_kwarg(key: str, pop_type: PopKwargType) -> None: if PopKwargType.CASE_INSENSITIVE == pop_type: - retval.append( - f'_{key} = case_insensitive_dict(kwargs.pop("{key}", {{}}) or {{}})' - ) + retval.append(f'_{key} = case_insensitive_dict(kwargs.pop("{key}", {{}}) or {{}})') elif PopKwargType.SIMPLE == pop_type: retval.append(f'_{key} = kwargs.pop("{key}", {{}}) or {{}}') @@ -189,35 +185,21 @@ def append_pop_kwarg(key: str, pop_type: PopKwargType) -> None: default_value = f"self._config.{kwarg.client_name}" else: default_value = kwarg.client_default_value_declaration - if check_kwarg_dict and ( - kwarg.location - in [ParameterLocation.HEADER, ParameterLocation.QUERY] - ): - kwarg_dict = ( - "headers" - if kwarg.location == ParameterLocation.HEADER - else "params" - ) + if check_kwarg_dict and (kwarg.location in [ParameterLocation.HEADER, ParameterLocation.QUERY]): + kwarg_dict = "headers" if kwarg.location == ParameterLocation.HEADER else "params" if ( kwarg.client_name == "api_version" and kwarg.code_model.options["multiapi"] and operation_name is not None ): - default_value = ( - f"self._api_version{operation_name} or {default_value}" - ) - default_value = ( - f"_{kwarg_dict}.pop('{kwarg.wire_name}', {default_value})" - ) + default_value = f"self._api_version{operation_name} or {default_value}" + default_value = f"_{kwarg_dict}.pop('{kwarg.wire_name}', {default_value})" retval.append( - f"{kwarg.client_name}: {type_annot} = kwargs.pop('{kwarg.client_name}', " - + f"{default_value})" + f"{kwarg.client_name}: {type_annot} = kwargs.pop('{kwarg.client_name}', " + f"{default_value})" ) else: - retval.append( - f"{kwarg.client_name}: {type_annot} = kwargs.pop('{kwarg.client_name}')" - ) + retval.append(f"{kwarg.client_name}: {type_annot} = kwargs.pop('{kwarg.client_name}')") return retval @staticmethod diff --git a/packages/autorest.python/autorest/codegen/serializers/request_builders_serializer.py b/packages/autorest.python/autorest/codegen/serializers/request_builders_serializer.py index 2cea2be7781..f9829843646 100644 --- a/packages/autorest.python/autorest/codegen/serializers/request_builders_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/request_builders_serializer.py @@ -48,7 +48,5 @@ def serialize_request_builders(self) -> str: imports=FileImportSerializer( self.imports, ), - request_builder_serializer=RequestBuilderSerializer( - self.code_model, async_mode=False - ), + request_builder_serializer=RequestBuilderSerializer(self.code_model, async_mode=False), ) diff --git a/packages/autorest.python/autorest/codegen/serializers/sample_serializer.py b/packages/autorest.python/autorest/codegen/serializers/sample_serializer.py index de775962ea9..ccf1e9dfe7a 100644 --- a/packages/autorest.python/autorest/codegen/serializers/sample_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/sample_serializer.py @@ -42,31 +42,23 @@ def __init__( self.operation = operation self.sample = sample self.file_name = file_name - self.sample_params = { - to_snake_case(k): v for k, v in sample.get("parameters", {}).items() - } + self.sample_params = {to_snake_case(k): v for k, v in sample.get("parameters", {}).items()} def _imports(self) -> FileImportSerializer: imports = FileImport(self.code_model) - namespace_from_package_name = get_namespace_from_package_name( - self.code_model.options["package_name"] - ) - namespace_config = get_namespace_config( - self.code_model.namespace, self.code_model.options["multiapi"] - ) + namespace_from_package_name = get_namespace_from_package_name(self.code_model.options["package_name"]) + namespace_config = get_namespace_config(self.code_model.namespace, self.code_model.options["multiapi"]) namespace = namespace_from_package_name or namespace_config # mainly for "azure-mgmt-rdbms" - if not self.code_model.options["multiapi"] and namespace_config.count( + if not self.code_model.options["multiapi"] and namespace_config.count(".") > namespace_from_package_name.count( "." - ) > namespace_from_package_name.count("."): + ): namespace = namespace_config client = self.code_model.clients[0] imports.add_submodule_import(namespace, client.name, ImportType.LOCAL) credential_type = getattr(client.credential, "type", None) if isinstance(credential_type, TokenCredentialType): - imports.add_submodule_import( - "azure.identity", "DefaultAzureCredential", ImportType.SDKCORE - ) + imports.add_submodule_import("azure.identity", "DefaultAzureCredential", ImportType.SDKCORE) elif isinstance(credential_type, KeyCredentialType): imports.add_import("os", ImportType.STDLIB) imports.add_submodule_import( @@ -75,11 +67,7 @@ def _imports(self) -> FileImportSerializer: ImportType.SDKCORE, ) for param in self.operation.parameters.positional: - if ( - not param.client_default_value - and not param.optional - and param.client_name in self.sample_params - ): + if not param.client_default_value and not param.optional and param.client_name in self.sample_params: imports.merge(param.type.imports_for_sample()) return FileImportSerializer(imports, True) @@ -90,14 +78,10 @@ def _client_params(self) -> Dict[str, Any]: if isinstance(credential_type, TokenCredentialType): special_param.update({"credential": "DefaultAzureCredential()"}) elif isinstance(credential_type, KeyCredentialType): - special_param.update( - {"credential": 'AzureKeyCredential(key=os.getenv("AZURE_KEY"))'} - ) + special_param.update({"credential": 'AzureKeyCredential(key=os.getenv("AZURE_KEY"))'}) params_positional = [ - p - for p in self.code_model.clients[0].parameters.positional - if not (p.optional or p.client_default_value) + p for p in self.code_model.clients[0].parameters.positional if not (p.optional or p.client_default_value) ] client_params = { p.client_name: special_param.get( @@ -119,11 +103,7 @@ def handle_param(param: Union[Parameter, BodyParameter], param_value: Any) -> st # prepare operation parameters def _operation_params(self) -> Dict[str, Any]: - params_positional = [ - p - for p in self.operation.parameters.positional - if not p.client_default_value - ] + params_positional = [p for p in self.operation.parameters.positional if not p.client_default_value] failure_info = "fail to find required param named {}" operation_params = {} for param in params_positional: @@ -131,12 +111,8 @@ def _operation_params(self) -> Dict[str, Any]: param_value = self.sample_params.get(name) if not param.optional: if not param_value: - raise Exception( # pylint: disable=broad-exception-raised - failure_info.format(name) - ) - operation_params[param.client_name] = self.handle_param( - param, param_value - ) + raise Exception(failure_info.format(name)) # pylint: disable=broad-exception-raised + operation_params[param.client_name] = self.handle_param(param, param_value) return operation_params def _operation_group_name(self) -> str: @@ -145,9 +121,7 @@ def _operation_group_name(self) -> str: return f".{self.operation_group.property_name}" def _operation_result(self) -> Tuple[str, str]: - is_response_none = "None" in self.operation.response_type_annotation( - async_mode=False - ) + is_response_none = "None" in self.operation.response_type_annotation(async_mode=False) lro = ".result()" if is_response_none: paging, normal_print, return_var = "", "", "" diff --git a/packages/autorest.python/autorest/codegen/serializers/test_serializer.py b/packages/autorest.python/autorest/codegen/serializers/test_serializer.py index d29fa8a106a..5314ff2c768 100644 --- a/packages/autorest.python/autorest/codegen/serializers/test_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/test_serializer.py @@ -119,9 +119,7 @@ def __init__( class TestGeneralSerializer(BaseSerializer): - def __init__( - self, code_model: CodeModel, env: Environment, *, is_async: bool = False - ) -> None: + def __init__(self, code_model: CodeModel, env: Environment, *, is_async: bool = False) -> None: super().__init__(code_model, env) self.is_async = is_async @@ -131,29 +129,19 @@ def aio_str(self) -> str: @property def test_names(self) -> List[TestName]: - return [ - TestName(c.name, is_async=self.is_async) for c in self.code_model.clients - ] + return [TestName(c.name, is_async=self.is_async) for c in self.code_model.clients] @property def import_clients(self) -> FileImportSerializer: imports = self.init_file_import() - namespace = get_namespace_from_package_name( - self.code_model.options["package_name"] - ) + namespace = get_namespace_from_package_name(self.code_model.options["package_name"]) - imports.add_submodule_import( - "devtools_testutils", "AzureRecordedTestCase", ImportType.STDLIB - ) + imports.add_submodule_import("devtools_testutils", "AzureRecordedTestCase", ImportType.STDLIB) if not self.is_async: imports.add_import("functools", ImportType.STDLIB) - imports.add_submodule_import( - "devtools_testutils", "PowerShellPreparer", ImportType.STDLIB - ) + imports.add_submodule_import("devtools_testutils", "PowerShellPreparer", ImportType.STDLIB) for client in self.code_model.clients: - imports.add_submodule_import( - namespace + self.aio_str, client.name, ImportType.STDLIB - ) + imports.add_submodule_import(namespace + self.aio_str, client.name, ImportType.STDLIB) return FileImportSerializer(imports, self.is_async) def serialize_conftest(self) -> str: @@ -194,9 +182,7 @@ def import_test(self) -> FileImportSerializer: test_name.base_test_class_name, ImportType.LOCAL, ) - imports.add_submodule_import( - "testpreparer", test_name.preparer_name, ImportType.LOCAL - ) + imports.add_submodule_import("testpreparer", test_name.preparer_name, ImportType.LOCAL) imports.add_submodule_import( "devtools_testutils" + self.aio_str, "recorded_by_proxy" + async_suffix, @@ -235,9 +221,7 @@ def get_operation_params(self, operation: OperationType) -> Dict[str, Any]: for param in required_params: model_type = self.get_model_type(param.type) param_type = self.get_sub_type(model_type) if model_type else param.type - operation_params[param.client_name] = json_dumps_template( - param_type.get_json_template_representation() - ) + operation_params[param.client_name] = json_dumps_template(param_type.get_json_template_representation()) return operation_params def get_test(self) -> Test: @@ -255,9 +239,7 @@ def get_test(self) -> Test: ) testcases.append(testcase) if not testcases: - raise Exception( # pylint: disable=broad-exception-raised - "no public operation to test" - ) + raise Exception("no public operation to test") # pylint: disable=broad-exception-raised return Test( client_name=self.client.name, @@ -270,9 +252,7 @@ def get_test(self) -> Test: @property def test_class_name(self) -> str: test_name = TestName(self.client.name, is_async=self.is_async) - class_name = ( - "" if self.operation_group.is_mixin else self.operation_group.class_name - ) + class_name = "" if self.operation_group.is_mixin else self.operation_group.class_name return f"Test{test_name.prefix}{class_name}{test_name.async_suffix_capt}" def serialize_test(self) -> str: diff --git a/packages/autorest.python/autorest/codegen/serializers/types_serializer.py b/packages/autorest.python/autorest/codegen/serializers/types_serializer.py index b57de478252..3e143f5209e 100644 --- a/packages/autorest.python/autorest/codegen/serializers/types_serializer.py +++ b/packages/autorest.python/autorest/codegen/serializers/types_serializer.py @@ -18,9 +18,7 @@ def imports(self) -> FileImport: ImportType.STDLIB, ) for nu in self.code_model.named_unions: - file_import.merge( - nu.imports(relative_path=".", model_typing=True, is_types_file=True) - ) + file_import.merge(nu.imports(relative_path=".", model_typing=True, is_types_file=True)) return file_import def serialize(self) -> str: diff --git a/packages/autorest.python/autorest/jsonrpc/__init__.py b/packages/autorest.python/autorest/jsonrpc/__init__.py index a5b6eca2030..59ebe000ea7 100644 --- a/packages/autorest.python/autorest/jsonrpc/__init__.py +++ b/packages/autorest.python/autorest/jsonrpc/__init__.py @@ -114,9 +114,7 @@ def get_value(self, key: str) -> Any: def message(self, channel: Channel, text: str) -> None: """Send a log message to autorest.""" - def get_boolean_value( - self, key: str, default: Optional[bool] = None - ) -> Optional[bool]: + def get_boolean_value(self, key: str, default: Optional[bool] = None) -> Optional[bool]: """Check if value is present on the line, and interpret it as bool if it was. If value is not not on the line, return the "default". diff --git a/packages/autorest.python/autorest/jsonrpc/server.py b/packages/autorest.python/autorest/jsonrpc/server.py index 87a27a29800..ab6ebb7a891 100644 --- a/packages/autorest.python/autorest/jsonrpc/server.py +++ b/packages/autorest.python/autorest/jsonrpc/server.py @@ -80,15 +80,11 @@ def Process(plugin_name: str, session_id: str) -> bool: def main() -> None: # If --python.debugger is specified on the command line, we call the server.py file internally # with flag --debug. - if "--debug" in sys.argv or os.environ.get( - "AUTOREST_PYTHON_ATTACH_VSCODE_DEBUG", False - ): + if "--debug" in sys.argv or os.environ.get("AUTOREST_PYTHON_ATTACH_VSCODE_DEBUG", False): try: import debugpy # pylint: disable=import-outside-toplevel except ImportError as exc: - raise SystemExit( - "Please pip install ptvsd in order to use VSCode debugging" - ) from exc + raise SystemExit("Please pip install ptvsd in order to use VSCode debugging") from exc # 5678 is the default attach port in the VS Code debug configurations debugpy.listen(("localhost", 5678)) @@ -101,9 +97,7 @@ def main() -> None: _LOGGER.debug("Trying to read") message = read_message() - response = typing.cast( - JSONRPC20Response, JSONRPCResponseManager.handle(message, dispatcher) - ).json + response = typing.cast(JSONRPC20Response, JSONRPCResponseManager.handle(message, dispatcher)).json _LOGGER.debug("Produced: %s", response) write_message(response) _LOGGER.debug("Message processed") diff --git a/packages/autorest.python/autorest/jsonrpc/stdstream.py b/packages/autorest.python/autorest/jsonrpc/stdstream.py index ab04e68800d..0fe3f02c696 100644 --- a/packages/autorest.python/autorest/jsonrpc/stdstream.py +++ b/packages/autorest.python/autorest/jsonrpc/stdstream.py @@ -72,25 +72,19 @@ def write_file(self, filename: Union[str, Path], file_content: str) -> None: def read_file(self, filename: Union[str, Path]) -> str: _LOGGER.debug("Asking content for file %s", filename) filename = os.fspath(filename) - request = JSONRPC20Request( - method="ReadFile", params=[self.session_id, filename], _id=42 - ) + request = JSONRPC20Request(method="ReadFile", params=[self.session_id, filename], _id=42) write_message(request.json) return json.loads(read_message())["result"] def list_inputs(self) -> List[str]: _LOGGER.debug("Calling list inputs to Autorest") - request = JSONRPC20Request( - method="ListInputs", params=[self.session_id, None], _id=42 - ) + request = JSONRPC20Request(method="ListInputs", params=[self.session_id, None], _id=42) write_message(request.json) return json.loads(read_message())["result"] def get_value(self, key: str) -> Any: _LOGGER.debug("Calling get value to Autorest: %s", key) - request = JSONRPC20Request( - method="GetValue", params=[self.session_id, key], _id=42 - ) + request = JSONRPC20Request(method="GetValue", params=[self.session_id, key], _id=42) write_message(request.json) return json.loads(read_message())["result"] @@ -101,7 +95,5 @@ def message(self, channel: Channel, text: str) -> None: "Channel": channel.value, "Text": text, } - request = JSONRPC20Request( - method="Message", params=[self.session_id, message], is_notification=True - ) + request = JSONRPC20Request(method="Message", params=[self.session_id, message], is_notification=True) write_message(request.json) diff --git a/packages/autorest.python/autorest/m2r/__init__.py b/packages/autorest.python/autorest/m2r/__init__.py index 93eb21c7061..88ea00c7f16 100644 --- a/packages/autorest.python/autorest/m2r/__init__.py +++ b/packages/autorest.python/autorest/m2r/__init__.py @@ -34,9 +34,7 @@ def update_yaml(self, yaml_data: Dict[str, Any]) -> None: """Convert in place the YAML str.""" self._convert_docstring_no_cycles(yaml_data, set()) - def _convert_docstring_no_cycles( - self, yaml_data: Union[Dict[str, Any], str], node_list: Set[int] - ) -> None: + def _convert_docstring_no_cycles(self, yaml_data: Union[Dict[str, Any], str], node_list: Set[int]) -> None: """Walk the YAML tree to convert MD to RST.""" if id(yaml_data) in node_list: return @@ -69,6 +67,4 @@ def get_options(self) -> Dict[str, Any]: if __name__ == "__main__": # CADL pipeline will call this args, unknown_args = parse_args() - M2R( - output_folder=args.output_folder, cadl_file=args.cadl_file, **unknown_args - ).process() + M2R(output_folder=args.output_folder, cadl_file=args.cadl_file, **unknown_args).process() diff --git a/packages/autorest.python/autorest/m4reformatter/__init__.py b/packages/autorest.python/autorest/m4reformatter/__init__.py index 63280665a26..ab4cfa8fd88 100644 --- a/packages/autorest.python/autorest/m4reformatter/__init__.py +++ b/packages/autorest.python/autorest/m4reformatter/__init__.py @@ -111,9 +111,7 @@ def update_enum(yaml_data: Dict[str, Any]) -> Dict[str, Any]: return base -def update_property( - yaml_data: Dict[str, Any], has_additional_properties: bool -) -> Dict[str, Any]: +def update_property(yaml_data: Dict[str, Any], has_additional_properties: bool) -> Dict[str, Any]: client_name = yaml_data["language"]["default"]["name"] if has_additional_properties and client_name == "additional_properties": client_name = "additional_properties1" @@ -150,9 +148,7 @@ def create_model(yaml_data: Dict[str, Any]) -> Dict[str, Any]: return base -def fill_model( - yaml_data: Dict[str, Any], current_model: Dict[str, Any] -) -> Dict[str, Any]: +def fill_model(yaml_data: Dict[str, Any], current_model: Dict[str, Any]) -> Dict[str, Any]: properties = [] yaml_parents = yaml_data.get("parents", {}).get("immediate", []) dict_parents = [p for p in yaml_parents if p["type"] == "dictionary"] @@ -170,17 +166,12 @@ def fill_model( } ) properties.extend( - [ - update_property(p, has_additional_properties=bool(dict_parents)) - for p in yaml_data.get("properties", []) - ] + [update_property(p, has_additional_properties=bool(dict_parents)) for p in yaml_data.get("properties", [])] ) current_model.update( { "properties": properties, - "parents": [ - update_type(yaml_data=p) for p in yaml_parents if p["type"] == "object" - ], + "parents": [update_type(yaml_data=p) for p in yaml_parents if p["type"] == "object"], "discriminatedSubtypes": update_discriminated_subtypes(yaml_data), "discriminatorValue": yaml_data.get("discriminatorValue"), } @@ -253,11 +244,7 @@ def update_types(yaml_data: List[Dict[str, Any]]) -> Dict[str, Any]: if KNOWN_TYPES.get(type["type"]): types.append(KNOWN_TYPES[type["type"]]) else: - types.append( - next( - v for v in ORIGINAL_ID_TO_UPDATED_TYPE.values() if id(v) == id(type) - ) - ) + types.append(next(v for v in ORIGINAL_ID_TO_UPDATED_TYPE.values() if id(v) == id(type))) retval = {"type": "combined", "types": types} ORIGINAL_ID_TO_UPDATED_TYPE[id(retval)] = retval return retval @@ -318,17 +305,11 @@ def add_lro_information( for response in operation["responses"]: response["pollerSync"] = extensions.get("x-python-custom-poller-sync") response["pollerAsync"] = extensions.get("x-python-custom-poller-async") - response["pollingMethodSync"] = extensions.get( - "x-python-custom-default-polling-method-sync" - ) - response["pollingMethodAsync"] = extensions.get( - "x-python-custom-default-polling-method-async" - ) + response["pollingMethodSync"] = extensions.get("x-python-custom-default-polling-method-sync") + response["pollingMethodAsync"] = extensions.get("x-python-custom-default-polling-method-async") -def filter_out_paging_next_operation( - yaml_data: List[Dict[str, Any]] -) -> List[Dict[str, Any]]: +def filter_out_paging_next_operation(yaml_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]: next_operations: Set[str] = set() for operation in yaml_data: next_operation = operation.get("nextOperation") @@ -355,13 +336,9 @@ def update_response( else: type = None return { - "headers": [ - update_response_header(h) - for h in yaml_data["protocol"]["http"].get("headers", []) - ], + "headers": [update_response_header(h) for h in yaml_data["protocol"]["http"].get("headers", [])], "statusCodes": [ - int(code) if code != "default" else "default" - for code in yaml_data["protocol"]["http"]["statusCodes"] + int(code) if code != "default" else "default" for code in yaml_data["protocol"]["http"]["statusCodes"] ], "type": type, "nullable": yaml_data.get("nullable", False), @@ -391,28 +368,20 @@ def _get_default_content_type( # pylint: disable=too-many-return-statements def update_client_url(yaml_data: Dict[str, Any]) -> str: - if any( - p - for p in yaml_data["globalParameters"] - if p["language"]["default"]["name"] == "$host" - ): + if any(p for p in yaml_data["globalParameters"] if p["language"]["default"]["name"] == "$host"): # this means we DO NOT have a parameterized host # in order to share code better, going to make it a "parameterized host" of # just the endpoint parameter return "{endpoint}" # we have a parameterized host. Return first url from first request, quite gross - return yaml_data["operationGroups"][0]["operations"][0]["requests"][0]["protocol"][ - "http" - ]["uri"] + return yaml_data["operationGroups"][0]["operations"][0]["requests"][0]["protocol"]["http"]["uri"] def to_lower_camel_case(name: str) -> str: return re.sub(r"_([a-z])", lambda x: x.group(1).upper(), name) -class M4Reformatter( - YamlUpdatePluginAutorest -): # pylint: disable=too-many-public-methods +class M4Reformatter(YamlUpdatePluginAutorest): # pylint: disable=too-many-public-methods """Add Python naming information.""" def __init__(self, *args, **kwargs) -> None: @@ -443,10 +412,7 @@ def only_path_and_body_parameters_positional(self) -> bool: @property def default_optional_constants_to_none(self) -> bool: - return bool( - self._autorestapi.get_boolean_value("default-optional-constants-to-none") - or self.version_tolerant - ) + return bool(self._autorestapi.get_boolean_value("default-optional-constants-to-none") or self.version_tolerant) def update_parameter_base( self, yaml_data: Dict[str, Any], *, override_client_name: Optional[str] = None @@ -456,14 +422,8 @@ def update_parameter_base( location = "other" if location == "uri": location = "endpointPath" - grouped_by = ( - yaml_data["groupedBy"]["language"]["default"]["name"] - if yaml_data.get("groupedBy") - else None - ) - client_name: str = ( - override_client_name or yaml_data["language"]["default"]["name"] - ) + grouped_by = yaml_data["groupedBy"]["language"]["default"]["name"] if yaml_data.get("groupedBy") else None + client_name: str = override_client_name or yaml_data["language"]["default"]["name"] if grouped_by and client_name[0] != "_": # this is an m4 bug, doesn't hide constant grouped params, patching m4 for now client_name = "_" + client_name @@ -502,17 +462,11 @@ def update_overloads( if not body_types: return overloads for body_type in body_types: - overload = self.update_overload( - group_name, yaml_data, body_type, content_types=content_types - ) - overload["internal"] = yaml_data.get("extensions", {}).get( - "x-ms-internal", False - ) + overload = self.update_overload(group_name, yaml_data, body_type, content_types=content_types) + overload["internal"] = yaml_data.get("extensions", {}).get("x-ms-internal", False) for parameter in overload["parameters"]: if parameter["wireName"].lower() == "content-type": - parameter["clientDefaultValue"] = overload["bodyParameter"][ - "defaultContentType" - ] + parameter["clientDefaultValue"] = overload["bodyParameter"]["defaultContentType"] overloads.append(overload) return overloads @@ -524,14 +478,9 @@ def _update_operation_helper( *, is_overload: bool = False, ) -> Dict[str, Any]: - in_overriden = ( - body_parameter["type"]["type"] == "combined" if body_parameter else False - ) + in_overriden = body_parameter["type"]["type"] == "combined" if body_parameter else False abstract = False - if body_parameter and ( - body_parameter.get("entries") - or len(body_parameter["type"].get("types", [])) > 2 - ): + if body_parameter and (body_parameter.get("entries") or len(body_parameter["type"].get("types", [])) > 2): # this means it's formdata or urlencoded, or there are more than 2 types of body abstract = True return { @@ -551,10 +500,7 @@ def _update_operation_helper( "exceptions": [ update_response(e) for e in yaml_data.get("exceptions", []) - if not ( - e.get("schema") - and e["schema"]["language"]["default"]["name"] == "CloudError" - ) + if not (e.get("schema") and e["schema"]["language"]["default"]["name"] == "CloudError") ], "groupName": group_name, "discriminator": "operation", @@ -564,12 +510,8 @@ def _update_operation_helper( "externalDocs": yaml_data.get("externalDocs"), } - def get_operation_creator( - self, yaml_data: Dict[str, Any] - ) -> Callable[[str, Dict[str, Any]], List[Dict[str, Any]]]: - lro_operation = yaml_data.get("extensions", {}).get( - "x-ms-long-running-operation" - ) + def get_operation_creator(self, yaml_data: Dict[str, Any]) -> Callable[[str, Dict[str, Any]], List[Dict[str, Any]]]: + lro_operation = yaml_data.get("extensions", {}).get("x-ms-long-running-operation") paging_operation = yaml_data.get("extensions", {}).get("x-ms-pageable") if lro_operation and paging_operation: return self.update_lro_paging_operation @@ -579,72 +521,50 @@ def get_operation_creator( return self.update_paging_operation return self.update_operation - def update_operation( - self, group_name: str, yaml_data: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def update_operation(self, group_name: str, yaml_data: Dict[str, Any]) -> List[Dict[str, Any]]: body_parameter = ( - self.update_body_parameter(yaml_data["requestMediaTypes"]) - if yaml_data.get("requestMediaTypes") - else None + self.update_body_parameter(yaml_data["requestMediaTypes"]) if yaml_data.get("requestMediaTypes") else None ) content_types = None operation = self._update_operation_helper(group_name, yaml_data, body_parameter) - operation["internal"] = yaml_data.get("extensions", {}).get( - "x-ms-internal", False - ) + operation["internal"] = yaml_data.get("extensions", {}).get("x-ms-internal", False) operation["overloads"] = self.update_overloads( group_name, yaml_data, body_parameter, content_types=content_types ) operation["samples"] = yaml_data.get("extensions", {}).get("x-ms-examples", {}) return [operation] - def add_paging_information( - self, group_name: str, operation: Dict[str, Any], yaml_data: Dict[str, Any] - ) -> None: + def add_paging_information(self, group_name: str, operation: Dict[str, Any], yaml_data: Dict[str, Any]) -> None: operation["discriminator"] = "paging" - operation["itemName"] = yaml_data["extensions"]["x-ms-pageable"].get( - "itemName", "value" - ) - operation["continuationTokenName"] = yaml_data["extensions"][ - "x-ms-pageable" - ].get("nextLinkName") + operation["itemName"] = yaml_data["extensions"]["x-ms-pageable"].get("itemName", "value") + operation["continuationTokenName"] = yaml_data["extensions"]["x-ms-pageable"].get("nextLinkName") returned_response_object = ( - operation["nextOperation"]["responses"][0] - if operation.get("nextOperation") - else operation["responses"][0] + operation["nextOperation"]["responses"][0] if operation.get("nextOperation") else operation["responses"][0] ) if self.version_tolerant: # if we're in version tolerant, hide the paging model returned_response_object["type"]["internal"] = True operation["itemType"] = next( - p["type"] - for p in returned_response_object["type"]["properties"] - if p["wireName"] == operation["itemName"] + p["type"] for p in returned_response_object["type"]["properties"] if p["wireName"] == operation["itemName"] ) if yaml_data["language"]["default"]["paging"].get("nextLinkOperation"): operation["nextOperation"] = self.update_operation( group_name=group_name, - yaml_data=yaml_data["language"]["default"]["paging"][ - "nextLinkOperation" - ], + yaml_data=yaml_data["language"]["default"]["paging"]["nextLinkOperation"], )[0] extensions = yaml_data["extensions"] for response in operation["responses"]: response["pagerSync"] = extensions.get("x-python-custom-pager-sync") response["pagerAsync"] = extensions.get("x-python-custom-pager-async") - def update_paging_operation( - self, group_name: str, yaml_data: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def update_paging_operation(self, group_name: str, yaml_data: Dict[str, Any]) -> List[Dict[str, Any]]: retval: List[Dict[str, Any]] = [] for base_operation in self.update_operation(group_name, yaml_data): self.add_paging_information(group_name, base_operation, yaml_data) retval.append(base_operation) return retval - def update_lro_paging_operation( - self, group_name: str, yaml_data: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def update_lro_paging_operation(self, group_name: str, yaml_data: Dict[str, Any]) -> List[Dict[str, Any]]: retval: List[Dict[str, Any]] = [] for operation in self.update_lro_operation(group_name, yaml_data): if operation.get("discriminator") == "lro": @@ -659,9 +579,7 @@ def update_lro_initial_operation(self, initial_operation: Dict[str, Any]): initial_operation["wantTracing"] = False return initial_operation - def update_lro_operation( - self, group_name: str, yaml_data: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def update_lro_operation(self, group_name: str, yaml_data: Dict[str, Any]) -> List[Dict[str, Any]]: retval: List[Dict[str, Any]] = [] for base_operation in self.update_operation(group_name, yaml_data): initial_operation = self.update_operation(group_name, yaml_data)[0] @@ -684,9 +602,7 @@ def update_overload( body_parameter = self.update_body_parameter_overload( yaml_data["requestMediaTypes"], body_type, content_types=content_types ) - return self._update_operation_helper( - group_name, yaml_data, body_parameter, is_overload=True - ) + return self._update_operation_helper(group_name, yaml_data, body_parameter, is_overload=True) def update_operation_group(self, yaml_data: Dict[str, Any]) -> Dict[str, Any]: property_name = yaml_data["language"]["default"]["name"] @@ -694,11 +610,7 @@ def update_operation_group(self, yaml_data: Dict[str, Any]) -> Dict[str, Any]: "propertyName": property_name, "className": property_name, "operations": filter_out_paging_next_operation( - [ - o - for ydo in yaml_data["operations"] - for o in self.get_operation_creator(ydo)(property_name, ydo) - ] + [o for ydo in yaml_data["operations"] for o in self.get_operation_creator(ydo)(property_name, ydo)] ), } @@ -718,28 +630,19 @@ def _update_body_parameter_helper( body_param["contentTypes"] = content_types or [ ct for ct, request in yaml_data.items() - if id(body_type) - == id( - ORIGINAL_ID_TO_UPDATED_TYPE[id(get_body_parameter(request)["schema"])] - ) + if id(body_type) == id(ORIGINAL_ID_TO_UPDATED_TYPE[id(get_body_parameter(request)["schema"])]) ] # get default content type - body_param["defaultContentType"] = _get_default_content_type( - body_param["contentTypes"] - ) + body_param["defaultContentType"] = _get_default_content_type(body_param["contentTypes"]) # python supports IO input with all kinds of content_types if body_type["type"] == "binary": body_param["contentTypes"] = content_types or list(yaml_data.keys()) if body_param["type"]["type"] == "constant": - if not body_param["optional"] or ( - body_param["optional"] and not self.default_optional_constants_to_none - ): + if not body_param["optional"] or (body_param["optional"] and not self.default_optional_constants_to_none): body_param["clientDefaultValue"] = body_type["value"] body_param["flattened"] = flattened body_param["isPartialBody"] = is_partial_body - body_param["wireName"] = body_param["wireName"] or to_lower_camel_case( - body_param["clientName"] - ) + body_param["wireName"] = body_param["wireName"] or to_lower_camel_case(body_param["clientName"]) return body_param def update_multipart_body_parameter( @@ -767,21 +670,15 @@ def update_multipart_body_parameter( def update_body_parameter(self, yaml_data: Dict[str, Any]) -> Dict[str, Any]: protocol_http = list(yaml_data.values())[0].get("protocol", {}).get("http", {}) if protocol_http.get("multipart"): - return self.update_multipart_body_parameter( - yaml_data, "files", "Multipart input for files." - ) + return self.update_multipart_body_parameter(yaml_data, "files", "Multipart input for files.") if protocol_http.get("knownMediaType") == "form": - return self.update_multipart_body_parameter( - yaml_data, "data", "Multipart input for form encoded data." - ) + return self.update_multipart_body_parameter(yaml_data, "data", "Multipart input for form encoded data.") body_types = get_all_body_types(yaml_data) if len(body_types) > 1 and not yaml_data.get("flattened"): body_type = update_types(body_types) else: body_type = body_types[0] - body_param = next( - p for sr in yaml_data.values() for p in sr["parameters"] if is_body(p) - ) + body_param = next(p for sr in yaml_data.values() for p in sr["parameters"] if is_body(p)) return self._update_body_parameter_helper(yaml_data, body_param, body_type) def update_body_parameter_overload( @@ -792,12 +689,8 @@ def update_body_parameter_overload( content_types: Optional[List[str]] = None, ) -> Dict[str, Any]: """For overloads we already know what body_type we want to go with""" - body_param = next( - p for sr in yaml_data.values() for p in sr["parameters"] if is_body(p) - ) - return self._update_body_parameter_helper( - yaml_data, body_param, body_type, content_types=content_types - ) + body_param = next(p for sr in yaml_data.values() for p in sr["parameters"] if is_body(p)) + return self._update_body_parameter_helper(yaml_data, body_param, body_type, content_types=content_types) def update_flattened_parameter( self, yaml_data: Dict[str, Any], body_parameter: Optional[Dict[str, Any]] @@ -805,13 +698,9 @@ def update_flattened_parameter( if not body_parameter: raise ValueError("Has to have a body parameter if it's flattened") # this means i'm a property that is part of a flattened model - target_property_name = yaml_data["targetProperty"]["language"]["default"][ - "name" - ] + target_property_name = yaml_data["targetProperty"]["language"]["default"]["name"] param = self.update_parameter(yaml_data) - body_parameter.setdefault("propertyToParameterName", {})[ - target_property_name - ] = param["clientName"] + body_parameter.setdefault("propertyToParameterName", {})[target_property_name] = param["clientName"] param["inFlattenedBody"] = True return param @@ -829,11 +718,7 @@ def _update_content_type_parameter( return yaml_data param = copy.deepcopy(yaml_data) param["schema"] = KNOWN_TYPES["string"] # override to string type - if ( - body_parameter["type"]["type"] == "binary" - and not body_parameter["defaultContentType"] - and not self.legacy - ): + if body_parameter["type"]["type"] == "binary" and not body_parameter["defaultContentType"] and not self.legacy: param["required"] = True else: param["required"] = False @@ -843,13 +728,8 @@ def _update_content_type_parameter( if not (in_overriden or in_overload): param["inDocstring"] = False elif in_overload: - description += ( - " Content type parameter for " - f"{get_body_type_for_description(body_parameter)} body." - ) - if not in_overload or ( - body_parameter["type"]["type"] == "binary" and len(request_media_types) > 1 - ): + description += " Content type parameter for " f"{get_body_type_for_description(body_parameter)} body." + if not in_overload or (body_parameter["type"]["type"] == "binary" and len(request_media_types) > 1): content_types = "'" + "', '".join(request_media_types) + "'" description += f" Known values are: {content_types}." if not in_overload and not in_overriden: @@ -872,9 +752,7 @@ def _update_parameters_helper( has_flattened_body = body_parameter and body_parameter.get("flattened") for param in parameters: client_name = param["language"]["default"]["name"] - if param["language"]["default"]["name"] == "$host" or ( - client_name in seen_client_names - ): + if param["language"]["default"]["name"] == "$host" or (client_name in seen_client_names): continue seen_client_names.add(client_name) if has_flattened_body and param.get("targetProperty"): @@ -889,10 +767,7 @@ def _update_parameters_helper( continue if is_body(param): continue - if ( - param["language"]["default"].get("serializedName").lower() - == "content-type" - ): + if param["language"]["default"].get("serializedName").lower() == "content-type": param = self._update_content_type_parameter( param, body_parameter, @@ -900,9 +775,7 @@ def _update_parameters_helper( in_overload=in_overload, in_overriden=in_overriden, ) - updated_param = self.update_parameter( - param, in_overload=in_overload, in_overriden=in_overriden - ) + updated_param = self.update_parameter(param, in_overload=in_overload, in_overriden=in_overriden) retval.append(updated_param) return retval @@ -955,8 +828,7 @@ def update_parameters( next( prop for prop in grouper["type"]["properties"] - if p["clientName"].lstrip("_") - in prop["groupedParameterNames"] # TODO: patching m4 + if p["clientName"].lstrip("_") in prop["groupedParameterNames"] # TODO: patching m4 )["clientName"]: p["clientName"] for p in all_params if p.get("groupedBy") == grouper_name @@ -971,14 +843,10 @@ def update_parameter( in_overload: bool = False, in_overriden: bool = False, ) -> Dict[str, Any]: - param_base = self.update_parameter_base( - yaml_data, override_client_name=override_client_name - ) + param_base = self.update_parameter_base(yaml_data, override_client_name=override_client_name) type = get_type(yaml_data["schema"]) if type["type"] == "constant": - if not param_base["optional"] or ( - param_base["optional"] and not self.default_optional_constants_to_none - ): + if not param_base["optional"] or (param_base["optional"] and not self.default_optional_constants_to_none): param_base["clientDefaultValue"] = type["value"] protocol_http = yaml_data["protocol"].get("http", {}) param_base.update( @@ -987,9 +855,7 @@ def update_parameter( "implementation": yaml_data["implementation"], "explode": protocol_http.get("explode", False), "inOverload": in_overload, - "skipUrlEncoding": yaml_data.get("extensions", {}).get( - "x-ms-skip-url-encoding", False - ), + "skipUrlEncoding": yaml_data.get("extensions", {}).get("x-ms-skip-url-encoding", False), "inDocstring": yaml_data.get("inDocstring", True), "inOverriden": in_overriden, "delimiter": update_parameter_delimiter(protocol_http.get("style")), @@ -997,9 +863,7 @@ def update_parameter( ) return param_base - def update_global_parameters( - self, yaml_data: List[Dict[str, Any]] - ) -> List[Dict[str, Any]]: + def update_global_parameters(self, yaml_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]: global_params: List[Dict[str, Any]] = [] for global_parameter in yaml_data: client_name: Optional[str] = None @@ -1009,13 +873,9 @@ def update_global_parameters( client_name = "endpoint" if self.version_tolerant else "base_url" global_parameter["language"]["default"]["description"] = "Service URL." - elif ( - global_parameter.get("origin") == "modelerfour:synthesized/api-version" - ): + elif global_parameter.get("origin") == "modelerfour:synthesized/api-version": self.check_client_input = True - param = self.update_parameter( - global_parameter, override_client_name=client_name - ) + param = self.update_parameter(global_parameter, override_client_name=client_name) if global_parameter.get("origin") == "modelerfour:synthesized/api-version": param["implementation"] = "Client" param["checkClientInput"] = False @@ -1033,9 +893,7 @@ def get_token_credential(self, credential_scopes: List[str]) -> Dict[str, Any]: update_type(retval) return retval - def update_credential_from_security( - self, yaml_data: Dict[str, Any] - ) -> Dict[str, Any]: + def update_credential_from_security(self, yaml_data: Dict[str, Any]) -> Dict[str, Any]: retval: Dict[str, Any] = {} for scheme in yaml_data.get("schemes", []): if scheme["type"] == OAUTH_TYPE: @@ -1049,13 +907,8 @@ def get_credential_scopes_from_flags(self, auth_policy: str) -> List[str]: if self.azure_arm: return ["https://management.azure.com/.default"] credential_scopes_temp = self._autorestapi.get_value("credential-scopes") - credential_scopes = ( - credential_scopes_temp.split(",") if credential_scopes_temp else None - ) - if ( - self._autorestapi.get_boolean_value("credential-scopes", False) - and not credential_scopes - ): + credential_scopes = credential_scopes_temp.split(",") if credential_scopes_temp else None + if self._autorestapi.get_boolean_value("credential-scopes", False) and not credential_scopes: raise ValueError( "--credential-scopes takes a list of scopes in comma separated format. " "For example: --credential-scopes=https://cognitiveservices.azure.com/.default" @@ -1073,10 +926,7 @@ def get_credential_scopes_from_flags(self, auth_policy: str) -> List[str]: def update_credential_from_flags(self) -> Dict[str, Any]: default_auth_policy = "BearerTokenCredentialPolicy" - auth_policy = ( - self._autorestapi.get_value("credential-default-policy-type") - or default_auth_policy - ) + auth_policy = self._autorestapi.get_value("credential-default-policy-type") or default_auth_policy credential_scopes = self.get_credential_scopes_from_flags(auth_policy) key = self._autorestapi.get_value("credential-key-header-name") if auth_policy.lower() in ( @@ -1101,14 +951,10 @@ def update_credential_from_flags(self) -> Dict[str, Any]: ) if not key: key = "api-key" - _LOGGER.info( - "Defaulting the AzureKeyCredentialPolicy header's name to 'api-key'" - ) + _LOGGER.info("Defaulting the AzureKeyCredentialPolicy header's name to 'api-key'") return get_azure_key_credential(key) - def update_credential( - self, yaml_data: Dict[str, Any], parameters: List[Dict[str, Any]] - ) -> None: + def update_credential(self, yaml_data: Dict[str, Any], parameters: List[Dict[str, Any]]) -> None: # then override with credential flags credential_flag = ( self._autorestapi.get_boolean_value("add-credentials", False) @@ -1135,19 +981,13 @@ def update_credential( parameters.append(credential) def update_client(self, yaml_data: Dict[str, Any]) -> Dict[str, Any]: - parameters = self.update_global_parameters( - yaml_data.get("globalParameters", []) - ) + parameters = self.update_global_parameters(yaml_data.get("globalParameters", [])) self.update_credential(yaml_data.get("security", {}), parameters) return { "name": yaml_data["language"]["default"]["name"], "description": yaml_data["info"].get("description"), "parameters": parameters, - "url": ( - update_client_url(yaml_data) - if yaml_data.get("globalParameters") - else "" - ), + "url": (update_client_url(yaml_data) if yaml_data.get("globalParameters") else ""), } def update_yaml(self, yaml_data: Dict[str, Any]) -> None: @@ -1159,10 +999,7 @@ def update_yaml(self, yaml_data: Dict[str, Any]) -> None: # First we update the types, so we can access for when we're creating parameters etc. for type_group, types in yaml_data["schemas"].items(): for t in types: - if ( - type_group == "objects" - and t["language"]["default"]["name"] == "CloudError" - ): + if type_group == "objects" and t["language"]["default"]["name"] == "CloudError": # we don't generate cloud error continue update_type(t) @@ -1172,9 +1009,7 @@ def update_yaml(self, yaml_data: Dict[str, Any]) -> None: yaml_data["clients"][0]["operationGroups"] = [ self.update_operation_group(og) for og in yaml_data["operationGroups"] ] - yaml_data["types"] = list(ORIGINAL_ID_TO_UPDATED_TYPE.values()) + list( - KNOWN_TYPES.values() - ) + yaml_data["types"] = list(ORIGINAL_ID_TO_UPDATED_TYPE.values()) + list(KNOWN_TYPES.values()) if yaml_data.get("globalParameters"): del yaml_data["globalParameters"] del yaml_data["info"] diff --git a/packages/autorest.python/autorest/multiapi/__init__.py b/packages/autorest.python/autorest/multiapi/__init__.py index c74b1c4020e..4b321cc8d97 100644 --- a/packages/autorest.python/autorest/multiapi/__init__.py +++ b/packages/autorest.python/autorest/multiapi/__init__.py @@ -66,9 +66,7 @@ def __init__( ) -> None: super().__init__(output_folder=Path(output_folder).resolve(), **kwargs) if input_package_name is None: - raise ValueError( - "package-name is required, either provide it as args or check your readme configuration" - ) + raise ValueError("package-name is required, either provide it as args or check your readme configuration") self.input_package_name = input_package_name _LOGGER.debug("Received package name %s", input_package_name) _LOGGER.debug("Received output-folder %s", output_folder) @@ -116,8 +114,7 @@ def preview_mode(self) -> bool: # If not, if it exists a stable API version for a global or RT, will always be used return cast( bool, - self.user_specified_default_api - and "preview" in self.user_specified_default_api, + self.user_specified_default_api and "preview" in self.user_specified_default_api, ) @property @@ -147,9 +144,7 @@ def mod_to_api_version(self) -> Dict[str, str]: total_api_version_list = metadata_json["total_api_version_list"] if not version: if total_api_version_list: - sys.exit( - f"Unable to match {total_api_version_list} to label {version_path.stem}" - ) + sys.exit(f"Unable to match {total_api_version_list} to label {version_path.stem}") else: sys.exit(f"Unable to extract api version of {version_path.stem}") mod_to_api_version[version_path.name] = version @@ -186,6 +181,4 @@ def __init__(self, **kwargs: Any) -> None: @property def serializer(self) -> MultiAPISerializer: - return MultiAPISerializerAutorest( - self._autorestapi, output_folder=self.output_folder - ) + return MultiAPISerializerAutorest(self._autorestapi, output_folder=self.output_folder) diff --git a/packages/autorest.python/autorest/multiapi/models/client.py b/packages/autorest.python/autorest/multiapi/models/client.py index 0c07c5bf51e..e0311161e52 100644 --- a/packages/autorest.python/autorest/multiapi/models/client.py +++ b/packages/autorest.python/autorest/multiapi/models/client.py @@ -16,9 +16,7 @@ def _extract_version(metadata_json: Dict[str, Any], version_path: Path) -> str: total_api_version_list = metadata_json["total_api_version_list"] if not version: if total_api_version_list: - sys.exit( - f"Unable to match {total_api_version_list} to label {version_path.stem}" - ) + sys.exit(f"Unable to match {total_api_version_list} to label {version_path.stem}") else: sys.exit(f"Unable to extract api version of {version_path.stem}") return version @@ -36,20 +34,14 @@ def __init__( self.filename = default_version_metadata["client"]["filename"] self.host_value = default_version_metadata["client"]["host_value"] self.description = default_version_metadata["client"]["description"] - self.client_side_validation = default_version_metadata["client"][ - "client_side_validation" - ] + self.client_side_validation = default_version_metadata["client"]["client_side_validation"] self.default_version_metadata = default_version_metadata self.version_path_to_metadata = version_path_to_metadata def imports(self, async_mode: bool) -> FileImport: imports_to_load = "async_imports" if async_mode else "sync_imports" - file_import = FileImport( - json.loads(self.default_version_metadata["client"][imports_to_load]) - ) - local_imports = file_import.imports.get(TypingSection.REGULAR, {}).get( - ImportType.LOCAL, {} - ) + file_import = FileImport(json.loads(self.default_version_metadata["client"][imports_to_load])) + local_imports = file_import.imports.get(TypingSection.REGULAR, {}).get(ImportType.LOCAL, {}) for key in local_imports: if re.search("^\\.*_serialization$", key): relative_path = ".." if async_mode else "." @@ -61,22 +53,16 @@ def imports(self, async_mode: bool) -> FileImport: def parameterized_host_template_to_api_version(self) -> Dict[str, List[str]]: parameterized_host_template_to_api_version: Dict[str, List[str]] = {} for version_path, metadata_json in self.version_path_to_metadata.items(): - parameterized_host_template = metadata_json["client"][ - "parameterized_host_template" - ] + parameterized_host_template = metadata_json["client"]["parameterized_host_template"] version = _extract_version(metadata_json, version_path) - parameterized_host_template_to_api_version.setdefault( - parameterized_host_template, [] - ).append(version) + parameterized_host_template_to_api_version.setdefault(parameterized_host_template, []).append(version) return parameterized_host_template_to_api_version @property def has_public_lro_operations(self) -> bool: has_public_lro_operations = False for _, metadata_json in self.version_path_to_metadata.items(): - current_client_has_public_lro_operations = metadata_json["client"][ - "has_public_lro_operations" - ] + current_client_has_public_lro_operations = metadata_json["client"]["has_public_lro_operations"] if current_client_has_public_lro_operations: has_public_lro_operations = True return has_public_lro_operations diff --git a/packages/autorest.python/autorest/multiapi/models/code_model.py b/packages/autorest.python/autorest/multiapi/models/code_model.py index 4cd4a89d136..6459f95459d 100644 --- a/packages/autorest.python/autorest/multiapi/models/code_model.py +++ b/packages/autorest.python/autorest/multiapi/models/code_model.py @@ -34,16 +34,10 @@ def __init__( self.azure_arm = default_version_metadata["client"]["azure_arm"] self.default_version_metadata = default_version_metadata self.version_path_to_metadata = version_path_to_metadata - self.client = Client( - self.azure_arm, default_version_metadata, version_path_to_metadata - ) + self.client = Client(self.azure_arm, default_version_metadata, version_path_to_metadata) self.config = Config(default_version_metadata) - self.operation_mixin_group = OperationMixinGroup( - version_path_to_metadata, default_api_version - ) - self.global_parameters = GlobalParameters( - default_version_metadata["global_parameters"] - ) + self.operation_mixin_group = OperationMixinGroup(version_path_to_metadata, default_api_version) + self.global_parameters = GlobalParameters(default_version_metadata["global_parameters"]) self.user_specified_default_api = user_specified_default_api self.options: Dict[str, Any] = {"flavor": "azure", "company_name": "Microsoft"} self.core_library = "azure.core" @@ -60,16 +54,12 @@ def operation_groups(self) -> List[OperationGroup]: operation_group_class_name, ) in operation_groups_metadata.items(): try: - operation_group = [ - og for og in operation_groups if og.name == operation_group_name - ][0] + operation_group = [og for og in operation_groups if og.name == operation_group_name][0] except IndexError: operation_group = OperationGroup(operation_group_name) operation_groups.append(operation_group) operation_group.append_available_api(version_path.name) - operation_group.append_api_class_name_pair( - version_path.name, operation_group_class_name - ) + operation_group.append_api_class_name_pair(version_path.name, operation_group_class_name) operation_groups.sort(key=lambda x: x.name) return operation_groups @@ -77,10 +67,7 @@ def operation_groups(self) -> List[OperationGroup]: def host_variable_name(self) -> str: if self.client.parameterized_host_template_to_api_version: return "base_url" - params = ( - self.global_parameters.parameters - + self.global_parameters.service_client_specific_global_parameters - ) + params = self.global_parameters.parameters + self.global_parameters.service_client_specific_global_parameters try: return next(p for p in params if p.name in ["endpoint", "base_url"]).name except StopIteration: @@ -121,8 +108,7 @@ def there_is_a_rt_that_contains_api_version(rt_dict, api_version): # First let's map operation groups to their available APIs versioned_dict = { - operation_group.name: operation_group.available_apis - for operation_group in self.operation_groups + operation_group.name: operation_group.available_apis for operation_group in self.operation_groups } # Now let's also include mixins to their available APIs @@ -144,9 +130,7 @@ def there_is_a_rt_that_contains_api_version(rt_dict, api_version): # If some others RT contains "local_default_api_version", and # if it's greater than the future default, danger, don't profile it if ( - there_is_a_rt_that_contains_api_version( - versioned_dict, local_default_api_version - ) + there_is_a_rt_that_contains_api_version(versioned_dict, local_default_api_version) and local_default_api_version > self.default_api_version ): continue @@ -155,7 +139,4 @@ def there_is_a_rt_that_contains_api_version(rt_dict, api_version): @property def default_models(self): - return sorted( - {self.default_api_version} - | {versions for _, versions in self.last_rt_list.items()} - ) + return sorted({self.default_api_version} | {versions for _, versions in self.last_rt_list.items()}) diff --git a/packages/autorest.python/autorest/multiapi/models/config.py b/packages/autorest.python/autorest/multiapi/models/config.py index 072124c3f16..6cd273c631e 100644 --- a/packages/autorest.python/autorest/multiapi/models/config.py +++ b/packages/autorest.python/autorest/multiapi/models/config.py @@ -16,9 +16,7 @@ def __init__(self, default_version_metadata: Dict[str, Any]): def imports(self, async_mode: bool) -> FileImport: imports_to_load = "async_imports" if async_mode else "sync_imports" - return FileImport( - json.loads(self.default_version_metadata["config"][imports_to_load]) - ) + return FileImport(json.loads(self.default_version_metadata["config"][imports_to_load])) def credential_call(self, async_mode: bool) -> str: if async_mode: diff --git a/packages/autorest.python/autorest/multiapi/models/global_parameters.py b/packages/autorest.python/autorest/multiapi/models/global_parameters.py index 14490eade3e..f4502297c67 100644 --- a/packages/autorest.python/autorest/multiapi/models/global_parameters.py +++ b/packages/autorest.python/autorest/multiapi/models/global_parameters.py @@ -33,31 +33,21 @@ def service_client_specific_global_parameters(self) -> List[GlobalParameter]: """Return global params specific to multiapi service client + config api_version, endpoint (re-adding it in specific are), and profile """ - service_client_params_sync = self.global_parameters_metadata[ - "service_client_specific" - ]["sync"] - service_client_params_async = self.global_parameters_metadata[ - "service_client_specific" - ]["async"] - - return _convert_global_parameters( - service_client_params_sync, service_client_params_async - ) + service_client_params_sync = self.global_parameters_metadata["service_client_specific"]["sync"] + service_client_params_async = self.global_parameters_metadata["service_client_specific"]["async"] + + return _convert_global_parameters(service_client_params_sync, service_client_params_async) @property def parameters(self) -> List[GlobalParameter]: global_parameters_metadata_sync = self.global_parameters_metadata["sync"] global_parameters_metadata_async = self.global_parameters_metadata["async"] - return _convert_global_parameters( - global_parameters_metadata_sync, global_parameters_metadata_async - ) + return _convert_global_parameters(global_parameters_metadata_sync, global_parameters_metadata_async) @property def constant_parameters(self) -> List[ConstantGlobalParameter]: return [ ConstantGlobalParameter(constant_name, constant_value) - for constant_name, constant_value in self.global_parameters_metadata[ - "constant" - ].items() + for constant_name, constant_value in self.global_parameters_metadata["constant"].items() ] diff --git a/packages/autorest.python/autorest/multiapi/models/imports.py b/packages/autorest.python/autorest/multiapi/models/imports.py index 1c4c44fa83a..f3e00da4d13 100644 --- a/packages/autorest.python/autorest/multiapi/models/imports.py +++ b/packages/autorest.python/autorest/multiapi/models/imports.py @@ -43,9 +43,7 @@ def __init__( Tuple[ str, Optional[str], - Tuple[ - Tuple[Tuple[int, int], str, Optional[str]] - ], + Tuple[Tuple[Tuple[int, int], str, Optional[str]]], ], ] ] @@ -125,9 +123,9 @@ def _add_import( ], convert_list_to_tuple(name_import), ) - self._imports.setdefault(typing_section, {}).setdefault( - import_type, {} - ).setdefault(from_section, set()).add(name_input) + self._imports.setdefault(typing_section, {}).setdefault(import_type, {}).setdefault(from_section, set()).add( + name_input + ) def add_submodule_import( self, @@ -175,6 +173,4 @@ def merge(self, file_import: "FileImport") -> None: for import_type, package_list in import_type_dict.items(): for package_name, module_list in package_list.items(): for module_name in module_list: - self._add_import( - package_name, import_type, module_name, typing_section - ) + self._add_import(package_name, import_type, module_name, typing_section) diff --git a/packages/autorest.python/autorest/multiapi/models/operation_mixin_group.py b/packages/autorest.python/autorest/multiapi/models/operation_mixin_group.py index 9ce6960e16e..0949c824edf 100644 --- a/packages/autorest.python/autorest/multiapi/models/operation_mixin_group.py +++ b/packages/autorest.python/autorest/multiapi/models/operation_mixin_group.py @@ -32,11 +32,7 @@ def imports(self, async_mode: bool) -> FileImport: return imports def typing_definitions(self, async_mode: bool) -> str: - key = ( - "sync_mixin_typing_definitions" - if async_mode - else "async_mixin_typing_definitions" - ) + key = "sync_mixin_typing_definitions" if async_mode else "async_mixin_typing_definitions" origin = "".join( [ metadata_json.get("operation_mixins", {}).get(key, "") @@ -45,22 +41,16 @@ def typing_definitions(self, async_mode: bool) -> str: ) return "\n".join(set(origin.split("\n"))) - def _use_metadata_of_default_api_version( - self, mixin_operations: List[MixinOperation] - ) -> List[MixinOperation]: + def _use_metadata_of_default_api_version(self, mixin_operations: List[MixinOperation]) -> List[MixinOperation]: default_api_version_path = [ version_path for version_path in self.version_path_to_metadata.keys() if version_path.name == self.default_api_version ][0] - default_version_metadata = self.version_path_to_metadata[ - default_api_version_path - ] + default_version_metadata = self.version_path_to_metadata[default_api_version_path] if not default_version_metadata.get("operation_mixins"): return mixin_operations - for name, metadata in default_version_metadata["operation_mixins"][ - "operations" - ].items(): + for name, metadata in default_version_metadata["operation_mixins"]["operations"].items(): if name.startswith("_"): continue mixin_operation = [mo for mo in mixin_operations if mo.name == name][0] @@ -81,9 +71,7 @@ def mixin_operations(self) -> List[MixinOperation]: if mixin_operation_name.startswith("_"): continue try: - mixin_operation = [ - mo for mo in mixin_operations if mo.name == mixin_operation_name - ][0] + mixin_operation = [mo for mo in mixin_operations if mo.name == mixin_operation_name][0] except IndexError: mixin_operation = MixinOperation( name=mixin_operation_name, diff --git a/packages/autorest.python/autorest/multiapi/serializers/__init__.py b/packages/autorest.python/autorest/multiapi/serializers/__init__.py index 518cc2906a6..99c2be1547d 100644 --- a/packages/autorest.python/autorest/multiapi/serializers/__init__.py +++ b/packages/autorest.python/autorest/multiapi/serializers/__init__.py @@ -27,13 +27,8 @@ } -def _method_signature_helper( - parameters: List[GlobalParameter], async_mode: bool -) -> List[str]: - return [ - p.signature(async_mode) - for p in sorted(parameters, key=lambda p: p.required, reverse=True) - ] +def _method_signature_helper(parameters: List[GlobalParameter], async_mode: bool) -> List[str]: + return [p.signature(async_mode) for p in sorted(parameters, key=lambda p: p.required, reverse=True)] def _get_file_path(filename: str, async_mode: bool) -> Path: @@ -62,39 +57,25 @@ def _render_template(file: str, **kwargs: Any) -> str: code_model.global_parameters.parameters + code_model.global_parameters.service_client_specific_global_parameters ) - positional_params = [ - p for p in all_params if p.method_location == "positional" - ] - keyword_only_params = [ - p for p in all_params if p.method_location == "keywordOnly" - ] + positional_params = [p for p in all_params if p.method_location == "positional"] + keyword_only_params = [p for p in all_params if p.method_location == "keywordOnly"] return template.render( code_model=code_model, async_mode=async_mode, - positional_params=_method_signature_helper( - positional_params, async_mode - ), - keyword_only_params=_method_signature_helper( - keyword_only_params, async_mode - ), + positional_params=_method_signature_helper(positional_params, async_mode), + keyword_only_params=_method_signature_helper(keyword_only_params, async_mode), **kwargs ) # serialize init file - self.write_file( - _get_file_path("__init__", async_mode), _render_template("init") - ) + self.write_file(_get_file_path("__init__", async_mode), _render_template("init")) # serialize service client file imports = FileImportSerializer(code_model.client.imports(async_mode)) - config_policies = build_policies( - code_model.azure_arm, async_mode, is_azure_flavor=True - ) + config_policies = build_policies(code_model.azure_arm, async_mode, is_azure_flavor=True) self.write_file( _get_file_path(code_model.client.filename, async_mode), - _render_template( - "client", imports=imports, config_policies=config_policies - ), + _render_template("client", imports=imports, config_policies=config_policies), ) # serialize config file @@ -158,7 +139,5 @@ def serialize(self, code_model: CodeModel, no_async: Optional[bool]) -> None: class MultiAPISerializerAutorest(MultiAPISerializer, ReaderAndWriterAutorest): - def __init__( - self, autorestapi: AutorestAPI, *, output_folder: Union[str, Path] - ) -> None: + def __init__(self, autorestapi: AutorestAPI, *, output_folder: Union[str, Path]) -> None: super().__init__(autorestapi=autorestapi, output_folder=output_folder) diff --git a/packages/autorest.python/autorest/multiapi/serializers/import_serializer.py b/packages/autorest.python/autorest/multiapi/serializers/import_serializer.py index a889a7082f1..39e2529f416 100644 --- a/packages/autorest.python/autorest/multiapi/serializers/import_serializer.py +++ b/packages/autorest.python/autorest/multiapi/serializers/import_serializer.py @@ -57,9 +57,7 @@ def _serialize_package( ) for submodule_name, alias, version_modules in versioned_modules: for n, (version, module_name, comment) in enumerate(version_modules): - buffer.append( - "{} sys.version_info >= {}:".format("if" if n == 0 else "elif", version) - ) + buffer.append("{} sys.version_info >= {}:".format("if" if n == 0 else "elif", version)) buffer.append( f" from {module_name} import {submodule_name}{f' as {alias}' if alias else ''}" f"{f' # {comment}' if comment else ''}" @@ -141,34 +139,24 @@ def __init__(self, file_import: FileImport, typing_definitions: str = "") -> Non def _switch_typing_section_key(self, new_key: TypingSection): switched_dictionary = {} - switched_dictionary[new_key] = self._file_import.imports[ - TypingSection.CONDITIONAL - ] + switched_dictionary[new_key] = self._file_import.imports[TypingSection.CONDITIONAL] return switched_dictionary - def _get_imports_dict( - self, baseline_typing_section: TypingSection, add_conditional_typing: bool - ): + def _get_imports_dict(self, baseline_typing_section: TypingSection, add_conditional_typing: bool): # If this is a python 3 file, our regular imports include the CONDITIONAL category # If this is not a python 3 file, our typing imports include the CONDITIONAL category file_import_copy = deepcopy(self._file_import) - if add_conditional_typing and self._file_import.imports.get( - TypingSection.CONDITIONAL - ): + if add_conditional_typing and self._file_import.imports.get(TypingSection.CONDITIONAL): # we switch the TypingSection key for the CONDITIONAL typing imports so we can merge # the imports together - switched_imports_dictionary = self._switch_typing_section_key( - baseline_typing_section - ) + switched_imports_dictionary = self._switch_typing_section_key(baseline_typing_section) switched_imports = FileImport(switched_imports_dictionary) file_import_copy.merge(switched_imports) return file_import_copy.imports.get(baseline_typing_section, {}) def _add_type_checking_import(self): if self._file_import.imports.get(TypingSection.TYPING): - self._file_import.add_submodule_import( - "typing", "TYPE_CHECKING", ImportType.STDLIB - ) + self._file_import.add_submodule_import("typing", "TYPE_CHECKING", ImportType.STDLIB) def __str__(self) -> str: self._add_type_checking_import() @@ -179,9 +167,7 @@ def __str__(self) -> str: ) if regular_imports_dict: - regular_imports = "\n\n".join( - _get_import_clauses(regular_imports_dict, "\n") - ) + regular_imports = "\n\n".join(_get_import_clauses(regular_imports_dict, "\n")) typing_imports = "" typing_imports_dict = self._get_imports_dict( @@ -190,8 +176,6 @@ def __str__(self) -> str: ) if typing_imports_dict: typing_imports += "\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n " - typing_imports += "\n\n ".join( - _get_import_clauses(typing_imports_dict, "\n ") - ) + typing_imports += "\n\n ".join(_get_import_clauses(typing_imports_dict, "\n ")) return regular_imports + typing_imports + self._typing_definitions diff --git a/packages/autorest.python/autorest/multiapi/utils.py b/packages/autorest.python/autorest/multiapi/utils.py index 2bc5651bfa5..0323c6ea530 100644 --- a/packages/autorest.python/autorest/multiapi/utils.py +++ b/packages/autorest.python/autorest/multiapi/utils.py @@ -25,17 +25,13 @@ def _get_default_api_version_from_list( # and change it automatically so I can take both syntax as input if user_specified_default_api and not user_specified_default_api.startswith("v"): default_api_version = [ - mod_api - for mod_api, real_api in mod_to_api_version.items() - if real_api == user_specified_default_api + mod_api for mod_api, real_api in mod_to_api_version.items() if real_api == user_specified_default_api ][0] _LOGGER.info("Default API version will be: %s", default_api_version) return default_api_version absolute_latest = sorted(api_versions_list)[-1] - not_preview_versions = [ - version for version in api_versions_list if "preview" not in version - ] + not_preview_versions = [version for version in api_versions_list if "preview" not in version] # If there is no preview, easy: the absolute latest is the only latest if not not_preview_versions: diff --git a/packages/autorest.python/autorest/multiclient/__init__.py b/packages/autorest.python/autorest/multiclient/__init__.py index da163edddc6..3d397f6b086 100644 --- a/packages/autorest.python/autorest/multiclient/__init__.py +++ b/packages/autorest.python/autorest/multiclient/__init__.py @@ -33,9 +33,7 @@ def process(self) -> bool: template = env.get_template("version.py.jinja2") self.write_file( Path("_version.py"), - template.render( - package_version=self.options.get("package-version") or "1.0.0b1" - ), + template.render(package_version=self.options.get("package-version") or "1.0.0b1"), ) # py.typed diff --git a/packages/autorest.python/autorest/postprocess/__init__.py b/packages/autorest.python/autorest/postprocess/__init__.py index b2749a9df82..a0f16378cee 100644 --- a/packages/autorest.python/autorest/postprocess/__init__.py +++ b/packages/autorest.python/autorest/postprocess/__init__.py @@ -22,9 +22,7 @@ def format_file(file: Path, file_content: str) -> str: if not file.suffix == ".py": return file_content try: - file_content = black.format_file_contents( - file_content, fast=True, mode=_BLACK_MODE - ) + file_content = black.format_file_contents(file_content, fast=True, mode=_BLACK_MODE) except NothingChanged: pass return file_content @@ -98,11 +96,7 @@ def get_namespace(self, dir: Path, namespace: str) -> Tuple[Path, str]: return self.get_namespace(next_dir, namespace) def process(self) -> bool: - folders = [ - f - for f in self.base_folder.glob("**/*") - if f.is_dir() and not f.stem.startswith("__") - ] + folders = [f for f in self.base_folder.glob("**/*") if f.is_dir() and not f.stem.startswith("__")] # will always have the root self.fix_imports_in_init( generated_file_name="_client", @@ -128,13 +122,9 @@ def process(self) -> bool: ) except StopIteration: pass - operations_folders = [ - f for f in folders if f.stem in ["operations", "_operations"] - ] + operations_folders = [f for f in folders if f.stem in ["operations", "_operations"]] for operations_folder in operations_folders: - sub_namespace = ".".join( - str(operations_folder.relative_to(self.base_folder)).split(os.sep) - ) + sub_namespace = ".".join(str(operations_folder.relative_to(self.base_folder)).split(os.sep)) self.fix_imports_in_init( generated_file_name="_operations", folder_path=operations_folder, @@ -143,9 +133,7 @@ def process(self) -> bool: shutil.rmtree(f"{str(self.output_folder)}/.temp_folder") return True - def fix_imports_in_init( - self, generated_file_name: str, folder_path: Path, namespace: str - ) -> None: + def fix_imports_in_init(self, generated_file_name: str, folder_path: Path, namespace: str) -> None: customized_objects_str = python_run( self.venv_context, command=[namespace, str(self.output_folder)], @@ -154,9 +142,7 @@ def fix_imports_in_init( if not customized_objects_str: return - customized_objects = { - k: None for k in customized_objects_str.split(",") - }.keys() # filter out duplicates + customized_objects = {k: None for k in customized_objects_str.split(",")}.keys() # filter out duplicates file = (folder_path / "__init__.py").relative_to(self.output_folder) file_content = self.read_file(file).replace("\r\n", "\n") added_objs = [] @@ -175,16 +161,12 @@ def fix_imports_in_init( "\nexcept ImportError:\n _patch_all = []", "", ) - file_content = file_content.replace( - "from ._patch import __all__ as _patch_all", "" - ) + file_content = file_content.replace("from ._patch import __all__ as _patch_all", "") file_content = file_content.replace( "from ._patch import * # pylint: disable=unused-wildcard-import\n", "", ) - file_content = file_content.replace( - "__all__.extend([p for p in _patch_all if p not in __all__])", "" - ) + file_content = file_content.replace("__all__.extend([p for p in _patch_all if p not in __all__])", "") if added_objs: # add import patch_sdk_import = "from ._patch import patch_sdk as _patch_sdk" @@ -196,9 +178,7 @@ def fix_imports_in_init( file_content = file_content.replace(patch_sdk_import, replacement) # add to __all__ added_objs_all = "\n".join([f' "{obj}",' for obj in added_objs]) + "\n" - file_content = file_content.replace( - "__all__ = [", f"__all__ = [\n{added_objs_all}", 1 - ) + file_content = file_content.replace("__all__ = [", f"__all__ = [\n{added_objs_all}", 1) formatted_file = format_file(file, file_content) self.write_file(file, formatted_file) diff --git a/packages/autorest.python/autorest/postprocess/get_all.py b/packages/autorest.python/autorest/postprocess/get_all.py index 642e392c4c6..4206e36a9c4 100644 --- a/packages/autorest.python/autorest/postprocess/get_all.py +++ b/packages/autorest.python/autorest/postprocess/get_all.py @@ -15,7 +15,5 @@ def main(namespace): if __name__ == "__main__": patched = ",".join(main(sys.argv[1])) output_folder = sys.argv[2] - with open( - f"{output_folder}/.temp_folder/patched.txt", "w", encoding="utf-8-sig" - ) as f: + with open(f"{output_folder}/.temp_folder/patched.txt", "w", encoding="utf-8-sig") as f: f.write(patched) diff --git a/packages/autorest.python/autorest/postprocess/venvtools.py b/packages/autorest.python/autorest/postprocess/venvtools.py index b465d044a9d..482cb9ee0ff 100644 --- a/packages/autorest.python/autorest/postprocess/venvtools.py +++ b/packages/autorest.python/autorest/postprocess/venvtools.py @@ -69,9 +69,7 @@ def python_run( # pylint: disable=inconsistent-return-statements stdout=False, ) if module == "get_all": - with open( - f"{command[1]}/.temp_folder/patched.txt", "r", encoding="utf-8-sig" - ) as f: + with open(f"{command[1]}/.temp_folder/patched.txt", "r", encoding="utf-8-sig") as f: return f.read() except subprocess.CalledProcessError as err: print(err) diff --git a/packages/autorest.python/autorest/preprocess/__init__.py b/packages/autorest.python/autorest/preprocess/__init__.py index f8eccb05fc8..70c18c7f566 100644 --- a/packages/autorest.python/autorest/preprocess/__init__.py +++ b/packages/autorest.python/autorest/preprocess/__init__.py @@ -30,18 +30,14 @@ def update_overload_section( if overload_s.get("type"): overload_s["type"] = original_s["type"] if overload_s.get("headers"): - for overload_h, original_h in zip( - overload_s["headers"], original_s["headers"] - ): + for overload_h, original_h in zip(overload_s["headers"], original_s["headers"]): if overload_h.get("type"): overload_h["type"] = original_h["type"] except KeyError as exc: raise ValueError(overload["name"]) from exc -def add_overload( - yaml_data: Dict[str, Any], body_type: Dict[str, Any], for_flatten_params=False -): +def add_overload(yaml_data: Dict[str, Any], body_type: Dict[str, Any], for_flatten_params=False): overload = copy.deepcopy(yaml_data) overload["isOverload"] = True overload["bodyParameter"]["type"] = body_type @@ -53,9 +49,7 @@ def add_overload( if for_flatten_params: overload["bodyParameter"]["flattened"] = True else: - overload["parameters"] = [ - p for p in overload["parameters"] if not p.get("inFlattenedBody") - ] + overload["parameters"] = [p for p in overload["parameters"] if not p.get("inFlattenedBody")] # for yaml sync, we need to make sure all of the responses, parameters, and exceptions' types have the same yaml id for overload_p, original_p in zip(overload["parameters"], yaml_data["parameters"]): overload_p["type"] = original_p["type"] @@ -63,9 +57,7 @@ def add_overload( update_overload_section(overload, yaml_data, "exceptions") # update content type to be an overloads content type - content_type_param = next( - p for p in overload["parameters"] if p["wireName"].lower() == "content-type" - ) + content_type_param = next(p for p in overload["parameters"] if p["wireName"].lower() == "content-type") content_type_param["inOverload"] = True content_type_param["inDocstring"] = True body_type_description = get_body_type_for_description(overload["bodyParameter"]) @@ -88,25 +80,16 @@ def add_overloads_for_body_param(yaml_data: Dict[str, Any]) -> None: body_parameter = yaml_data["bodyParameter"] if not ( body_parameter["type"]["type"] == "combined" - and len(yaml_data["bodyParameter"]["type"]["types"]) - > len(yaml_data["overloads"]) + and len(yaml_data["bodyParameter"]["type"]["types"]) > len(yaml_data["overloads"]) ): return for body_type in body_parameter["type"]["types"]: - if any( - o - for o in yaml_data["overloads"] - if id(o["bodyParameter"]["type"]) == id(body_type) - ): + if any(o for o in yaml_data["overloads"] if id(o["bodyParameter"]["type"]) == id(body_type)): continue yaml_data["overloads"].append(add_overload(yaml_data, body_type)) if body_type.get("type") == "model" and body_type.get("base") == "json": - yaml_data["overloads"].append( - add_overload(yaml_data, body_type, for_flatten_params=True) - ) - content_type_param = next( - p for p in yaml_data["parameters"] if p["wireName"].lower() == "content-type" - ) + yaml_data["overloads"].append(add_overload(yaml_data, body_type, for_flatten_params=True)) + content_type_param = next(p for p in yaml_data["parameters"] if p["wireName"].lower() == "content-type") content_type_param["inOverload"] = False content_type_param["inOverriden"] = True content_type_param["inDocstring"] = True @@ -116,9 +99,7 @@ def add_overloads_for_body_param(yaml_data: Dict[str, Any]) -> None: content_type_param["optional"] = True -def update_description( - description: Optional[str], default_description: str = "" -) -> str: +def update_description(description: Optional[str], default_description: str = "") -> str: if not description: description = default_description description.rstrip(" ") @@ -179,9 +160,7 @@ def has_json_content_type(yaml_data: Dict[str, Any]) -> bool: def has_multi_part_content_type(yaml_data: Dict[str, Any]) -> bool: - return any( - ct for ct in yaml_data.get("contentTypes", []) if ct == "multipart/form-data" - ) + return any(ct for ct in yaml_data.get("contentTypes", []) if ct == "multipart/form-data") class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method @@ -213,8 +192,7 @@ def add_body_param_type( body_parameter and body_parameter["type"]["type"] in ("model", "dict", "list") and ( - has_json_content_type(body_parameter) - or (self.is_cadl and has_multi_part_content_type(body_parameter)) + has_json_content_type(body_parameter) or (self.is_cadl and has_multi_part_content_type(body_parameter)) ) and not body_parameter["type"].get("xmlMetadata") and not any(t for t in ["flattened", "groupedBy"] if body_parameter.get(t)) @@ -240,10 +218,7 @@ def pad_reserved_words(self, name: str, pad_type: PadType): return name if self.is_cadl: - reserved_words = { - k: (v + CADL_RESERVED_WORDS.get(k, [])) - for k, v in RESERVED_WORDS.items() - } + reserved_words = {k: (v + CADL_RESERVED_WORDS.get(k, [])) for k, v in RESERVED_WORDS.items()} else: reserved_words = RESERVED_WORDS name = pad_special_chars(name) @@ -256,26 +231,18 @@ def pad_reserved_words(self, name: str, pad_type: PadType): def update_types(self, yaml_data: List[Dict[str, Any]]) -> None: for type in yaml_data: for property in type.get("properties", []): - property["description"] = update_description( - property.get("description", "") - ) - property["clientName"] = self.pad_reserved_words( - property["clientName"].lower(), PadType.PROPERTY - ) + property["description"] = update_description(property.get("description", "")) + property["clientName"] = self.pad_reserved_words(property["clientName"].lower(), PadType.PROPERTY) add_redefined_builtin_info(property["clientName"], property) if type.get("name"): name = self.pad_reserved_words(type["name"], PadType.MODEL) type["name"] = name[0].upper() + name[1:] - type["description"] = update_description( - type.get("description", ""), type["name"] - ) + type["description"] = update_description(type.get("description", ""), type["name"]) type["snakeCaseName"] = to_snake_case(type["name"]) if type.get("values"): # we're enums for value in type["values"]: - padded_name = self.pad_reserved_words( - value["name"].lower(), PadType.ENUM - ).upper() + padded_name = self.pad_reserved_words(value["name"].lower(), PadType.ENUM).upper() if padded_name[0] in "0123456789": padded_name = "ENUM_" + padded_name value["name"] = padded_name @@ -286,24 +253,16 @@ def update_types(self, yaml_data: List[Dict[str, Any]]) -> None: yaml_data.append(v["type"]) def update_client(self, yaml_data: Dict[str, Any]) -> None: - yaml_data["description"] = update_description( - yaml_data["description"], default_description=yaml_data["name"] - ) + yaml_data["description"] = update_description(yaml_data["description"], default_description=yaml_data["name"]) yaml_data["legacyFilename"] = to_snake_case(yaml_data["name"].replace(" ", "_")) parameters = yaml_data["parameters"] for parameter in parameters: self.update_parameter(parameter) if parameter["clientName"] == "credential": policy = parameter["type"].get("policy") - if ( - policy - and policy["type"] == "BearerTokenCredentialPolicy" - and self.azure_arm - ): + if policy and policy["type"] == "BearerTokenCredentialPolicy" and self.azure_arm: policy["type"] = "ARMChallengeAuthenticationPolicy" - policy["credentialScopes"] = [ - "https://management.azure.com/.default" - ] + policy["credentialScopes"] = ["https://management.azure.com/.default"] if ( (not self.version_tolerant or self.azure_arm) and parameters @@ -321,10 +280,7 @@ def update_client(self, yaml_data: Dict[str, Any]) -> None: property_if_none_match = None for p in o["parameters"]: wire_name_lower = get_wire_name_lower(p) - if ( - p["location"] == "header" - and wire_name_lower == "client-request-id" - ): + if p["location"] == "header" and wire_name_lower == "client-request-id": yaml_data["requestIdHeaderName"] = wire_name_lower if self.version_tolerant and p["location"] == "header": if wire_name_lower == "if-match": @@ -346,16 +302,13 @@ def update_client(self, yaml_data: Dict[str, Any]) -> None: o["parameters"] = [ item for item in o["parameters"] - if get_wire_name_lower(item) - not in ("if-match", "if-none-match") + if get_wire_name_lower(item) not in ("if-match", "if-none-match") ] + [property_if_match, property_if_none_match] o["hasEtag"] = True yaml_data["hasEtag"] = True - def get_operation_updater( - self, yaml_data: Dict[str, Any] - ) -> Callable[[Dict[str, Any], Dict[str, Any]], None]: + def get_operation_updater(self, yaml_data: Dict[str, Any]) -> Callable[[Dict[str, Any], Dict[str, Any]], None]: if yaml_data["discriminator"] == "lropaging": return self.update_lro_paging_operation if yaml_data["discriminator"] == "lro": @@ -366,13 +319,8 @@ def get_operation_updater( def update_parameter(self, yaml_data: Dict[str, Any]) -> None: yaml_data["description"] = update_description(yaml_data.get("description", "")) - if not ( - yaml_data["location"] == "header" - and yaml_data["clientName"] in ("content_type", "accept") - ): - yaml_data["clientName"] = self.pad_reserved_words( - yaml_data["clientName"].lower(), PadType.PARAMETER - ) + if not (yaml_data["location"] == "header" and yaml_data["clientName"] in ("content_type", "accept")): + yaml_data["clientName"] = self.pad_reserved_words(yaml_data["clientName"].lower(), PadType.PARAMETER) if yaml_data.get("propertyToParameterName"): # need to create a new one with padded keys and values yaml_data["propertyToParameterName"] = { @@ -383,20 +331,12 @@ def update_parameter(self, yaml_data: Dict[str, Any]) -> None: } wire_name_lower = (yaml_data.get("wireName") or "").lower() if yaml_data["location"] == "header" and ( - wire_name_lower in HEADERS_HIDE_IN_METHOD - or yaml_data.get("clientDefaultValue") == "multipart/form-data" + wire_name_lower in HEADERS_HIDE_IN_METHOD or yaml_data.get("clientDefaultValue") == "multipart/form-data" ): yaml_data["hideInMethod"] = True - if ( - self.version_tolerant - and yaml_data["location"] == "header" - and wire_name_lower in HEADERS_CONVERT_IN_METHOD - ): + if self.version_tolerant and yaml_data["location"] == "header" and wire_name_lower in HEADERS_CONVERT_IN_METHOD: headers_convert(yaml_data, HEADERS_CONVERT_IN_METHOD[wire_name_lower]) - if ( - wire_name_lower in ["$host", "content-type", "accept"] - and yaml_data["type"]["type"] == "constant" - ): + if wire_name_lower in ["$host", "content-type", "accept"] and yaml_data["type"]["type"] == "constant": yaml_data["clientDefaultValue"] = yaml_data["type"]["value"] def update_operation( @@ -406,15 +346,11 @@ def update_operation( *, is_overload: bool = False, ) -> None: - yaml_data["groupName"] = self.pad_reserved_words( - yaml_data["groupName"], PadType.OPERATION_GROUP - ) + yaml_data["groupName"] = self.pad_reserved_words(yaml_data["groupName"], PadType.OPERATION_GROUP) yaml_data["groupName"] = to_snake_case(yaml_data["groupName"]) yaml_data["name"] = yaml_data["name"].lower() yaml_data["name"] = self.pad_reserved_words(yaml_data["name"], PadType.METHOD) - yaml_data["description"] = update_description( - yaml_data["description"], yaml_data["name"] - ) + yaml_data["description"] = update_description(yaml_data["description"], yaml_data["name"]) yaml_data["summary"] = update_description(yaml_data.get("summary", "")) body_parameter = yaml_data.get("bodyParameter") for parameter in yaml_data["parameters"]: @@ -435,12 +371,8 @@ def update_operation( def _update_lro_operation_helper(self, yaml_data: Dict[str, Any]) -> None: for response in yaml_data.get("responses", []): response["discriminator"] = "lro" - response["pollerSync"] = ( - response.get("pollerSync") or "azure.core.polling.LROPoller" - ) - response["pollerAsync"] = ( - response.get("pollerAsync") or "azure.core.polling.AsyncLROPoller" - ) + response["pollerSync"] = response.get("pollerSync") or "azure.core.polling.LROPoller" + response["pollerAsync"] = response.get("pollerAsync") or "azure.core.polling.AsyncLROPoller" if not response.get("pollingMethodSync"): response["pollingMethodSync"] = ( "azure.mgmt.core.polling.arm_polling.ARMPolling" @@ -462,9 +394,7 @@ def update_lro_paging_operation( item_type: Optional[Dict[str, Any]] = None, ) -> None: self.update_lro_operation(code_model, yaml_data, is_overload=is_overload) - self.update_paging_operation( - code_model, yaml_data, is_overload=is_overload, item_type=item_type - ) + self.update_paging_operation(code_model, yaml_data, is_overload=is_overload, item_type=item_type) yaml_data["discriminator"] = "lropaging" for response in yaml_data.get("responses", []): response["discriminator"] = "lropaging" @@ -483,15 +413,11 @@ def update_lro_operation( is_overload: bool = False, ) -> None: self.update_operation(code_model, yaml_data, is_overload=is_overload) - self.update_operation( - code_model, yaml_data["initialOperation"], is_overload=is_overload - ) + self.update_operation(code_model, yaml_data["initialOperation"], is_overload=is_overload) self._update_lro_operation_helper(yaml_data) for overload in yaml_data.get("overloads", []): self._update_lro_operation_helper(overload) - self.update_operation( - code_model, overload["initialOperation"], is_overload=True - ) + self.update_operation(code_model, overload["initialOperation"], is_overload=True) def update_paging_operation( self, @@ -506,9 +432,7 @@ def update_paging_operation( yaml_data["nextOperation"]["groupName"] = self.pad_reserved_words( yaml_data["nextOperation"]["groupName"], PadType.OPERATION_GROUP ) - yaml_data["nextOperation"]["groupName"] = to_snake_case( - yaml_data["nextOperation"]["groupName"] - ) + yaml_data["nextOperation"]["groupName"] = to_snake_case(yaml_data["nextOperation"]["groupName"]) for response in yaml_data["nextOperation"].get("responses", []): update_paging_response(response) response["itemType"] = item_type @@ -516,28 +440,20 @@ def update_paging_operation( update_paging_response(response) response["itemType"] = item_type for overload in yaml_data.get("overloads", []): - self.update_paging_operation( - code_model, overload, is_overload=True, item_type=item_type - ) + self.update_paging_operation(code_model, overload, is_overload=True, item_type=item_type) - def update_operation_groups( - self, code_model: Dict[str, Any], client: Dict[str, Any] - ) -> None: + def update_operation_groups(self, code_model: Dict[str, Any], client: Dict[str, Any]) -> None: operation_groups_yaml_data = client["operationGroups"] for operation_group in operation_groups_yaml_data: operation_group["identifyName"] = self.pad_reserved_words( operation_group.get("name", operation_group["propertyName"]), PadType.OPERATION_GROUP, ) - operation_group["identifyName"] = to_snake_case( - operation_group["identifyName"] - ) + operation_group["identifyName"] = to_snake_case(operation_group["identifyName"]) operation_group["propertyName"] = self.pad_reserved_words( operation_group["propertyName"], PadType.OPERATION_GROUP ) - operation_group["propertyName"] = to_snake_case( - operation_group["propertyName"] - ) + operation_group["propertyName"] = to_snake_case(operation_group["propertyName"]) operation_group["className"] = update_operation_group_class_name( client["name"], operation_group["className"] ) @@ -574,6 +490,4 @@ def get_options(self) -> Dict[str, Any]: if __name__ == "__main__": # CADL pipeline will call this args, unknown_args = parse_args() - PreProcessPlugin( - output_folder=args.output_folder, cadl_file=args.cadl_file, **unknown_args - ).process() + PreProcessPlugin(output_folder=args.output_folder, cadl_file=args.cadl_file, **unknown_args).process() diff --git a/packages/autorest.python/install.py b/packages/autorest.python/install.py index 3e265eab516..14ae38dd278 100644 --- a/packages/autorest.python/install.py +++ b/packages/autorest.python/install.py @@ -6,6 +6,7 @@ # license information. # -------------------------------------------------------------------------- import sys + if not sys.version_info >= (3, 8, 0): raise Exception("Autorest for Python extension requires Python 3.8 at least") @@ -45,5 +46,6 @@ def main(): python_run(venv_context, "pip", ["install", "-r", "requirements.txt"]) python_run(venv_context, "pip", ["install", "-e", str(_ROOT_DIR)]) + if __name__ == "__main__": main() diff --git a/packages/autorest.python/prepare.py b/packages/autorest.python/prepare.py index 828d3e9ff46..84b592e30ee 100644 --- a/packages/autorest.python/prepare.py +++ b/packages/autorest.python/prepare.py @@ -6,6 +6,7 @@ # license information. # -------------------------------------------------------------------------- import sys + if not sys.version_info >= (3, 8, 0): raise Exception("Autorest for Python extension requires Python 3.8 at least") @@ -25,9 +26,10 @@ def main(): env_builder = venv.EnvBuilder(with_pip=True) venv_context = env_builder.ensure_directories(venv_path) - requirements_path = _ROOT_DIR / 'dev_requirements.txt' + requirements_path = _ROOT_DIR / "dev_requirements.txt" python_run(venv_context, "pip", ["install", "-r", str(requirements_path)]) + if __name__ == "__main__": main() diff --git a/packages/autorest.python/run_cadl.py b/packages/autorest.python/run_cadl.py index 512b7dfb704..acc4404a90d 100644 --- a/packages/autorest.python/run_cadl.py +++ b/packages/autorest.python/run_cadl.py @@ -26,9 +26,7 @@ try: import debugpy # pylint: disable=import-outside-toplevel except ImportError: - raise SystemExit( - "Please pip install ptvsd in order to use VSCode debugging" - ) + raise SystemExit("Please pip install ptvsd in order to use VSCode debugging") # 5678 is the default attach port in the VS Code debug configurations debugpy.listen(("localhost", 5678)) diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/__init__.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/__init__.py index b54d40dbd2f..09a500e6f5c 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/__init__.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/__init__.py @@ -7,10 +7,12 @@ # -------------------------------------------------------------------------- from ._multiapi_service_client import MultiapiServiceClient -__all__ = ['MultiapiServiceClient'] + +__all__ = ["MultiapiServiceClient"] try: from ._patch import patch_sdk # type: ignore + patch_sdk() except ImportError: pass diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_configuration.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_configuration.py index 01c1c4907c2..88bc35f69e9 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_configuration.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_configuration.py @@ -19,6 +19,7 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential + class MultiapiServiceClientConfiguration: """Configuration for MultiapiServiceClient. @@ -29,32 +30,27 @@ class MultiapiServiceClientConfiguration: :type credential: ~azure.core.credentials.TokenCredential """ - def __init__( - self, - credential: "TokenCredential", - **kwargs: Any - ): + def __init__(self, credential: "TokenCredential", **kwargs: Any): if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'azure-multiapi-sample/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "azure-multiapi-sample/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ): - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any): + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = ARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_multiapi_service_client.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_multiapi_service_client.py index e6fd8370f07..c870376931e 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_multiapi_service_client.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_multiapi_service_client.py @@ -25,6 +25,7 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential + class _SDKClient(object): def __init__(self, *args, **kwargs): """This is a fake class to support current implemetation of MultiApiClientMixin." @@ -32,6 +33,7 @@ def __init__(self, *args, **kwargs): """ pass + class MultiapiServiceClient(MultiapiServiceClientOperationsMixin, MultiApiClientMixin, _SDKClient): """Service client for multiapi client testing. @@ -54,28 +56,30 @@ class MultiapiServiceClient(MultiapiServiceClientOperationsMixin, MultiApiClient :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - DEFAULT_API_VERSION = '3.0.0' + DEFAULT_API_VERSION = "3.0.0" _PROFILE_TAG = "azure.multiapi.sample.MultiapiServiceClient" - LATEST_PROFILE = ProfileDefinition({ - _PROFILE_TAG: { - None: DEFAULT_API_VERSION, - 'begin_test_lro': '1.0.0', - 'begin_test_lro_and_paging': '1.0.0', - 'test_one': '2.0.0', - }}, - _PROFILE_TAG + " latest" + LATEST_PROFILE = ProfileDefinition( + { + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + "begin_test_lro": "1.0.0", + "begin_test_lro_and_paging": "1.0.0", + "test_one": "2.0.0", + } + }, + _PROFILE_TAG + " latest", ) def __init__( self, credential: "TokenCredential", - api_version: Optional[str]=None, + api_version: Optional[str] = None, base_url: str = "http://localhost:3000", - profile: KnownProfiles=KnownProfiles.default, + profile: KnownProfiles = KnownProfiles.default, **kwargs: Any ): if api_version: - kwargs.setdefault('api_version', api_version) + kwargs.setdefault("api_version", api_version) self._config = MultiapiServiceClientConfiguration(credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -96,10 +100,7 @@ def __init__( self._config.http_logging_policy, ] self._client = ARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) - super(MultiapiServiceClient, self).__init__( - api_version=api_version, - profile=profile - ) + super(MultiapiServiceClient, self).__init__(api_version=api_version, profile=profile) @classmethod def _models_dict(cls, api_version): @@ -109,18 +110,21 @@ def _models_dict(cls, api_version): def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: - * 1.0.0: :mod:`v1.models` - * 2.0.0: :mod:`v2.models` - * 3.0.0: :mod:`v3.models` + * 1.0.0: :mod:`v1.models` + * 2.0.0: :mod:`v2.models` + * 3.0.0: :mod:`v3.models` """ - if api_version == '1.0.0': + if api_version == "1.0.0": from .v1 import models + return models - elif api_version == '2.0.0': + elif api_version == "2.0.0": from .v2 import models + return models - elif api_version == '3.0.0': + elif api_version == "3.0.0": from .v3 import models + return models raise ValueError("API version {} is not available".format(api_version)) @@ -128,43 +132,57 @@ def models(cls, api_version=DEFAULT_API_VERSION): def operation_group_one(self): """Instance depends on the API version: - * 1.0.0: :class:`OperationGroupOneOperations` - * 2.0.0: :class:`OperationGroupOneOperations` - * 3.0.0: :class:`OperationGroupOneOperations` + * 1.0.0: :class:`OperationGroupOneOperations` + * 2.0.0: :class:`OperationGroupOneOperations` + * 3.0.0: :class:`OperationGroupOneOperations` """ - api_version = self._get_api_version('operation_group_one') - if api_version == '1.0.0': + api_version = self._get_api_version("operation_group_one") + if api_version == "1.0.0": from .v1.operations import OperationGroupOneOperations as OperationClass - elif api_version == '2.0.0': + elif api_version == "2.0.0": from .v2.operations import OperationGroupOneOperations as OperationClass - elif api_version == '3.0.0': + elif api_version == "3.0.0": from .v3.operations import OperationGroupOneOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'operation_group_one'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) + return OperationClass( + self._client, + self._config, + Serializer(self._models_dict(api_version)), + Deserializer(self._models_dict(api_version)), + api_version, + ) @property def operation_group_two(self): """Instance depends on the API version: - * 2.0.0: :class:`OperationGroupTwoOperations` - * 3.0.0: :class:`OperationGroupTwoOperations` + * 2.0.0: :class:`OperationGroupTwoOperations` + * 3.0.0: :class:`OperationGroupTwoOperations` """ - api_version = self._get_api_version('operation_group_two') - if api_version == '2.0.0': + api_version = self._get_api_version("operation_group_two") + if api_version == "2.0.0": from .v2.operations import OperationGroupTwoOperations as OperationClass - elif api_version == '3.0.0': + elif api_version == "3.0.0": from .v3.operations import OperationGroupTwoOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'operation_group_two'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) + return OperationClass( + self._client, + self._config, + Serializer(self._models_dict(api_version)), + Deserializer(self._models_dict(api_version)), + api_version, + ) def close(self): self._client.close() + def __enter__(self): self._client.__enter__() return self + def __exit__(self, *exc_details): self._client.__exit__(*exc_details) diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_operations_mixin.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_operations_mixin.py index d56bebf8cec..188dbeeeaa0 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_operations_mixin.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_operations_mixin.py @@ -21,9 +21,7 @@ class MultiapiServiceClientOperationsMixin(object): def begin_test_lro( - self, - product: Optional[Union[_models.Product, IO[bytes]]] = None, - **kwargs: Any + self, product: Optional[Union[_models.Product, IO[bytes]]] = None, **kwargs: Any ) -> LROPoller[_models.Product]: """Put in whatever shape of Product you want, will return a Product with id equal to 100. @@ -34,8 +32,8 @@ def begin_test_lro( :rtype: ~azure.core.polling.LROPoller[~azure.multiapi.sample.v1.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('begin_test_lro') - if api_version == '1.0.0': + api_version = self._get_api_version("begin_test_lro") + if api_version == "1.0.0": from .v1.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'begin_test_lro'".format(api_version)) @@ -66,8 +64,8 @@ def begin_test_lro_and_paging( ~azure.core.polling.LROPoller[~azure.core.paging.ItemPaged[~azure.multiapi.sample.v1.models.Product]] :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('begin_test_lro_and_paging') - if api_version == '1.0.0': + api_version = self._get_api_version("begin_test_lro_and_paging") + if api_version == "1.0.0": from .v1.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'begin_test_lro_and_paging'".format(api_version)) @@ -99,12 +97,12 @@ def test_different_calls( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('test_different_calls') - if api_version == '1.0.0': + api_version = self._get_api_version("test_different_calls") + if api_version == "1.0.0": from .v1.operations import MultiapiServiceClientOperationsMixin as OperationClass - elif api_version == '2.0.0': + elif api_version == "2.0.0": from .v2.operations import MultiapiServiceClientOperationsMixin as OperationClass - elif api_version == '3.0.0': + elif api_version == "3.0.0": from .v3.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'test_different_calls'".format(api_version)) @@ -115,13 +113,12 @@ def test_different_calls( # pylint: disable=inconsistent-return-statements mixin_instance._serialize = Serializer(self._models_dict(api_version)) mixin_instance._serialize.client_side_validation = False mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) - return mixin_instance.test_different_calls(greeting_in_english, greeting_in_chinese, greeting_in_french, **kwargs) + return mixin_instance.test_different_calls( + greeting_in_english, greeting_in_chinese, greeting_in_french, **kwargs + ) def test_one( # pylint: disable=inconsistent-return-statements - self, - id: int, - message: Optional[str] = None, - **kwargs: Any + self, id: int, message: Optional[str] = None, **kwargs: Any ) -> None: """TestOne should be in an FirstVersionOperationsMixin. @@ -133,10 +130,10 @@ def test_one( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('test_one') - if api_version == '1.0.0': + api_version = self._get_api_version("test_one") + if api_version == "1.0.0": from .v1.operations import MultiapiServiceClientOperationsMixin as OperationClass - elif api_version == '2.0.0': + elif api_version == "2.0.0": from .v2.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'test_one'".format(api_version)) @@ -149,18 +146,15 @@ def test_one( # pylint: disable=inconsistent-return-statements mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) return mixin_instance.test_one(id, message, **kwargs) - def test_paging( - self, - **kwargs: Any - ) -> Iterable["_models.ModelThree"]: + def test_paging(self, **kwargs: Any) -> Iterable["_models.ModelThree"]: """Returns ModelThree with optionalProperty 'paged'. :return: An iterator like instance of either ModelThree or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.multiapi.sample.v3.models.ModelThree] :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('test_paging') - if api_version == '3.0.0': + api_version = self._get_api_version("test_paging") + if api_version == "3.0.0": from .v3.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'test_paging'".format(api_version)) diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_serialization.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_serialization.py index 75e26c415d2..2f781d74082 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_serialization.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_serialization.py @@ -349,9 +349,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: def as_dict( self, keep_readonly: bool = True, - key_transformer: Callable[ - [str, Dict[str, Any], Any], Any - ] = attribute_transformer, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, **kwargs: Any ) -> JSON: """Return a dict that can be serialized using json.dump. @@ -540,7 +538,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]]=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -748,7 +746,7 @@ def query(self, name, data, data_type, **kwargs): # Treat the list aside, since we don't want to encode the div separator if data_type.startswith("["): internal_data_type = data_type[1:-1] - do_quote = not kwargs.get('skip_quote', False) + do_quote = not kwargs.get("skip_quote", False) return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization @@ -907,12 +905,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): raise serialized.append(None) - if kwargs.get('do_quote', False): - serialized = [ - '' if s is None else quote(str(s), safe='') - for s - in serialized - ] + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] if div: serialized = ["" if s is None else str(s) for s in serialized] @@ -1369,7 +1363,7 @@ class Deserializer(object): valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]]=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None): self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_version.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_version.py index a30a458f8b5..780a1be7a6e 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_version.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/_version.py @@ -5,4 +5,4 @@ # license information. # -------------------------------------------------------------------------- -VERSION = "0.1.0" \ No newline at end of file +VERSION = "0.1.0" diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/__init__.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/__init__.py index c5088f7a288..5dc86527950 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/__init__.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/__init__.py @@ -7,4 +7,5 @@ # -------------------------------------------------------------------------- from ._multiapi_service_client import MultiapiServiceClient -__all__ = ['MultiapiServiceClient'] + +__all__ = ["MultiapiServiceClient"] diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_configuration.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_configuration.py index 09ba5dda158..ce9df4f2a2b 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_configuration.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_configuration.py @@ -19,6 +19,7 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential + class MultiapiServiceClientConfiguration: """Configuration for MultiapiServiceClient. @@ -29,32 +30,27 @@ class MultiapiServiceClientConfiguration: :type credential: ~azure.core.credentials_async.AsyncTokenCredential """ - def __init__( - self, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: + def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.credential = credential - self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'azure-multiapi-sample/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "azure-multiapi-sample/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or ARMHttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_multiapi_service_client.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_multiapi_service_client.py index 775c8af1c81..0238fbaff72 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_multiapi_service_client.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_multiapi_service_client.py @@ -25,6 +25,7 @@ # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential + class _SDKClient(object): def __init__(self, *args, **kwargs): """This is a fake class to support current implemetation of MultiApiClientMixin." @@ -32,6 +33,7 @@ def __init__(self, *args, **kwargs): """ pass + class MultiapiServiceClient(MultiapiServiceClientOperationsMixin, MultiApiClientMixin, _SDKClient): """Service client for multiapi client testing. @@ -54,16 +56,18 @@ class MultiapiServiceClient(MultiapiServiceClientOperationsMixin, MultiApiClient :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ - DEFAULT_API_VERSION = '3.0.0' + DEFAULT_API_VERSION = "3.0.0" _PROFILE_TAG = "azure.multiapi.sample.MultiapiServiceClient" - LATEST_PROFILE = ProfileDefinition({ - _PROFILE_TAG: { - None: DEFAULT_API_VERSION, - 'begin_test_lro': '1.0.0', - 'begin_test_lro_and_paging': '1.0.0', - 'test_one': '2.0.0', - }}, - _PROFILE_TAG + " latest" + LATEST_PROFILE = ProfileDefinition( + { + _PROFILE_TAG: { + None: DEFAULT_API_VERSION, + "begin_test_lro": "1.0.0", + "begin_test_lro_and_paging": "1.0.0", + "test_one": "2.0.0", + } + }, + _PROFILE_TAG + " latest", ) def __init__( @@ -75,7 +79,7 @@ def __init__( **kwargs: Any ) -> None: if api_version: - kwargs.setdefault('api_version', api_version) + kwargs.setdefault("api_version", api_version) self._config = MultiapiServiceClientConfiguration(credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -96,10 +100,7 @@ def __init__( self._config.http_logging_policy, ] self._client = AsyncARMPipelineClient(base_url=base_url, policies=_policies, **kwargs) - super(MultiapiServiceClient, self).__init__( - api_version=api_version, - profile=profile - ) + super(MultiapiServiceClient, self).__init__(api_version=api_version, profile=profile) @classmethod def _models_dict(cls, api_version): @@ -109,18 +110,21 @@ def _models_dict(cls, api_version): def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: - * 1.0.0: :mod:`v1.models` - * 2.0.0: :mod:`v2.models` - * 3.0.0: :mod:`v3.models` + * 1.0.0: :mod:`v1.models` + * 2.0.0: :mod:`v2.models` + * 3.0.0: :mod:`v3.models` """ - if api_version == '1.0.0': + if api_version == "1.0.0": from ..v1 import models + return models - elif api_version == '2.0.0': + elif api_version == "2.0.0": from ..v2 import models + return models - elif api_version == '3.0.0': + elif api_version == "3.0.0": from ..v3 import models + return models raise ValueError("API version {} is not available".format(api_version)) @@ -128,43 +132,57 @@ def models(cls, api_version=DEFAULT_API_VERSION): def operation_group_one(self): """Instance depends on the API version: - * 1.0.0: :class:`OperationGroupOneOperations` - * 2.0.0: :class:`OperationGroupOneOperations` - * 3.0.0: :class:`OperationGroupOneOperations` + * 1.0.0: :class:`OperationGroupOneOperations` + * 2.0.0: :class:`OperationGroupOneOperations` + * 3.0.0: :class:`OperationGroupOneOperations` """ - api_version = self._get_api_version('operation_group_one') - if api_version == '1.0.0': + api_version = self._get_api_version("operation_group_one") + if api_version == "1.0.0": from ..v1.aio.operations import OperationGroupOneOperations as OperationClass - elif api_version == '2.0.0': + elif api_version == "2.0.0": from ..v2.aio.operations import OperationGroupOneOperations as OperationClass - elif api_version == '3.0.0': + elif api_version == "3.0.0": from ..v3.aio.operations import OperationGroupOneOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'operation_group_one'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) + return OperationClass( + self._client, + self._config, + Serializer(self._models_dict(api_version)), + Deserializer(self._models_dict(api_version)), + api_version, + ) @property def operation_group_two(self): """Instance depends on the API version: - * 2.0.0: :class:`OperationGroupTwoOperations` - * 3.0.0: :class:`OperationGroupTwoOperations` + * 2.0.0: :class:`OperationGroupTwoOperations` + * 3.0.0: :class:`OperationGroupTwoOperations` """ - api_version = self._get_api_version('operation_group_two') - if api_version == '2.0.0': + api_version = self._get_api_version("operation_group_two") + if api_version == "2.0.0": from ..v2.aio.operations import OperationGroupTwoOperations as OperationClass - elif api_version == '3.0.0': + elif api_version == "3.0.0": from ..v3.aio.operations import OperationGroupTwoOperations as OperationClass else: raise ValueError("API version {} does not have operation group 'operation_group_two'".format(api_version)) self._config.api_version = api_version - return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)), api_version) + return OperationClass( + self._client, + self._config, + Serializer(self._models_dict(api_version)), + Deserializer(self._models_dict(api_version)), + api_version, + ) async def close(self): await self._client.close() + async def __aenter__(self): await self._client.__aenter__() return self + async def __aexit__(self, *exc_details): await self._client.__aexit__(*exc_details) diff --git a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_operations_mixin.py b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_operations_mixin.py index 941bf57f663..9a990cda16c 100644 --- a/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_operations_mixin.py +++ b/packages/autorest.python/samples/specification/multiapi/generated/azure/multiapi/sample/aio/_operations_mixin.py @@ -21,9 +21,7 @@ class MultiapiServiceClientOperationsMixin(object): async def begin_test_lro( - self, - product: Optional[Union[_models.Product, IO[bytes]]] = None, - **kwargs: Any + self, product: Optional[Union[_models.Product, IO[bytes]]] = None, **kwargs: Any ) -> AsyncLROPoller[_models.Product]: """Put in whatever shape of Product you want, will return a Product with id equal to 100. @@ -35,8 +33,8 @@ async def begin_test_lro( :rtype: ~azure.core.polling.AsyncLROPoller[~azure.multiapi.sample.v1.models.Product] :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('begin_test_lro') - if api_version == '1.0.0': + api_version = self._get_api_version("begin_test_lro") + if api_version == "1.0.0": from ..v1.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'begin_test_lro'".format(api_version)) @@ -67,8 +65,8 @@ async def begin_test_lro_and_paging( ~azure.core.polling.AsyncLROPoller[~azure.core.async_paging.AsyncItemPaged[~azure.multiapi.sample.v1.models.Product]] :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('begin_test_lro_and_paging') - if api_version == '1.0.0': + api_version = self._get_api_version("begin_test_lro_and_paging") + if api_version == "1.0.0": from ..v1.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'begin_test_lro_and_paging'".format(api_version)) @@ -100,12 +98,12 @@ async def test_different_calls( # pylint: disable=inconsistent-return-statement :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('test_different_calls') - if api_version == '1.0.0': + api_version = self._get_api_version("test_different_calls") + if api_version == "1.0.0": from ..v1.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass - elif api_version == '2.0.0': + elif api_version == "2.0.0": from ..v2.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass - elif api_version == '3.0.0': + elif api_version == "3.0.0": from ..v3.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'test_different_calls'".format(api_version)) @@ -116,13 +114,12 @@ async def test_different_calls( # pylint: disable=inconsistent-return-statement mixin_instance._serialize = Serializer(self._models_dict(api_version)) mixin_instance._serialize.client_side_validation = False mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) - return await mixin_instance.test_different_calls(greeting_in_english, greeting_in_chinese, greeting_in_french, **kwargs) + return await mixin_instance.test_different_calls( + greeting_in_english, greeting_in_chinese, greeting_in_french, **kwargs + ) async def test_one( # pylint: disable=inconsistent-return-statements - self, - id: int, - message: Optional[str] = None, - **kwargs: Any + self, id: int, message: Optional[str] = None, **kwargs: Any ) -> None: """TestOne should be in an FirstVersionOperationsMixin. @@ -134,10 +131,10 @@ async def test_one( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('test_one') - if api_version == '1.0.0': + api_version = self._get_api_version("test_one") + if api_version == "1.0.0": from ..v1.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass - elif api_version == '2.0.0': + elif api_version == "2.0.0": from ..v2.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'test_one'".format(api_version)) @@ -150,18 +147,15 @@ async def test_one( # pylint: disable=inconsistent-return-statements mixin_instance._deserialize = Deserializer(self._models_dict(api_version)) return await mixin_instance.test_one(id, message, **kwargs) - def test_paging( - self, - **kwargs: Any - ) -> AsyncIterable["_models.ModelThree"]: + def test_paging(self, **kwargs: Any) -> AsyncIterable["_models.ModelThree"]: """Returns ModelThree with optionalProperty 'paged'. :return: An iterator like instance of either ModelThree or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.multiapi.sample.v3.models.ModelThree] :raises ~azure.core.exceptions.HttpResponseError: """ - api_version = self._get_api_version('test_paging') - if api_version == '3.0.0': + api_version = self._get_api_version("test_paging") + if api_version == "3.0.0": from ..v3.aio.operations import MultiapiServiceClientOperationsMixin as OperationClass else: raise ValueError("API version {} does not have operation 'test_paging'".format(api_version)) diff --git a/packages/autorest.python/setup.py b/packages/autorest.python/setup.py index f1d20bf53c3..b22fa2172ca 100644 --- a/packages/autorest.python/setup.py +++ b/packages/autorest.python/setup.py @@ -13,42 +13,42 @@ from setuptools import setup, find_packages - # Version extraction inspired from 'requests' -with open(os.path.join('autorest', '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) +with open(os.path.join("autorest", "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: - raise RuntimeError('Cannot find version information') + raise RuntimeError("Cannot find version information") setup( name="autorest", version=version, - description='Microsoft Autorest Plugins for Python', - long_description=open('README.md', 'r').read(), - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='azpysdkhelp@microsoft.com', - url='https://github.com/Azure/autorest.python', + description="Microsoft Autorest Plugins for Python", + long_description=open("README.md", "r").read(), + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/autorest.python", classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'License :: OSI Approved :: MIT License', + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "License :: OSI Approved :: MIT License", ], - packages=find_packages(exclude=[ - 'test', - ]), + packages=find_packages( + exclude=[ + "test", + ] + ), install_requires=[ "json-rpc", - "Jinja2 >= 2.11", # I need "include" and auto-context + blank line are not indented by default + "Jinja2 >= 2.11", # I need "include" and auto-context + blank line are not indented by default "pyyaml", "m2r2", "black", diff --git a/packages/autorest.python/start.py b/packages/autorest.python/start.py index 6fcedb04910..fdf57593653 100644 --- a/packages/autorest.python/start.py +++ b/packages/autorest.python/start.py @@ -6,6 +6,7 @@ # license information. # -------------------------------------------------------------------------- import sys + if not sys.version_info >= (3, 8, 0): raise Exception("Autorest for Python extension requires Python 3.8 at least") @@ -30,5 +31,6 @@ def main(): venv_context = env_builder.ensure_directories(venv_path) python_run(venv_context, "autorest.jsonrpc.server", command=sys.argv[1:]) + if __name__ == "__main__": main() diff --git a/packages/autorest.python/tasks.py b/packages/autorest.python/tasks.py index 4f4a549d3b5..9971000e3f5 100644 --- a/packages/autorest.python/tasks.py +++ b/packages/autorest.python/tasks.py @@ -19,7 +19,8 @@ ####################################################### # Working around for issue https://github.com/pyinvoke/invoke/issues/833 in python3.11 import inspect -if not hasattr(inspect, 'getargspec'): + +if not hasattr(inspect, "getargspec"): inspect.getargspec = inspect.getfullargspec ####################################################### @@ -46,49 +47,49 @@ class Config(NamedTuple): AUTOREST_DIR = os.path.dirname(__file__) M4_VERSION = "--use=@autorest/modelerfour@latest " _VANILLA_SWAGGER_MAPPINGS = { - 'AdditionalProperties': 'additionalProperties.json', - 'Anything': 'any-type.json', - 'ParameterFlattening': 'parameter-flattening.json', - 'BodyArray': 'body-array.json', - 'BodyBinary': 'body-binary.json', - 'BodyBoolean': 'body-boolean.json', - 'BodyByte': 'body-byte.json', - 'BodyComplex': 'body-complex.json', - 'BodyDate': 'body-date.json', - 'BodyDateTime': 'body-datetime.json', - 'BodyDateTimeRfc1123': 'body-datetime-rfc1123.json', - 'BodyDuration': 'body-duration.json', - 'BodyDictionary': 'body-dictionary.json', - 'BodyFile': 'body-file.json', - 'Constants': 'constants.json', - 'BodyFormData': 'body-formdata.json', - 'BodyFormUrlEncodedData': 'body-formdata-urlencoded.json', - 'BodyInteger': 'body-integer.json', - 'BodyNumber': 'body-number.json', - 'BodyString': 'body-string.json', - 'BodyTime': 'body-time.json', - 'ClientEnum': 'client-enum.json', - 'ErrorWithSecrets': 'error-with-secrets.json', - 'ExtensibleEnums': 'extensible-enums-swagger.json', - 'Header': 'header.json', - 'Http': 'httpInfrastructure.json', - 'IncorrectErrorResponse': 'incorrect-error-response.json', - 'Report': 'report.json', - 'RequiredOptional': 'required-optional.json', - 'Url': 'url.json', - 'Validation': 'validation.json', - 'CustomBaseUri': 'custom-baseUrl.json', - 'CustomBaseUriMoreOptions': 'custom-baseUrl-more-options.json', - 'MergePatchJson': 'merge-patch.json', - 'ModelFlattening': 'model-flattening.json', - 'Xml': 'xml-service.json', - 'UrlMultiCollectionFormat': 'url-multi-collectionFormat.json', - 'XmsErrorResponse': 'xms-error-responses.json', - 'MediaTypes': 'media_types.json', - 'ObjectType': 'object-type.json', - 'NonStringEnums': 'non-string-enum.json', - 'MultipleInheritance': 'multiple-inheritance.json', - 'NoOperations': 'no-operations.json', + "AdditionalProperties": "additionalProperties.json", + "Anything": "any-type.json", + "ParameterFlattening": "parameter-flattening.json", + "BodyArray": "body-array.json", + "BodyBinary": "body-binary.json", + "BodyBoolean": "body-boolean.json", + "BodyByte": "body-byte.json", + "BodyComplex": "body-complex.json", + "BodyDate": "body-date.json", + "BodyDateTime": "body-datetime.json", + "BodyDateTimeRfc1123": "body-datetime-rfc1123.json", + "BodyDuration": "body-duration.json", + "BodyDictionary": "body-dictionary.json", + "BodyFile": "body-file.json", + "Constants": "constants.json", + "BodyFormData": "body-formdata.json", + "BodyFormUrlEncodedData": "body-formdata-urlencoded.json", + "BodyInteger": "body-integer.json", + "BodyNumber": "body-number.json", + "BodyString": "body-string.json", + "BodyTime": "body-time.json", + "ClientEnum": "client-enum.json", + "ErrorWithSecrets": "error-with-secrets.json", + "ExtensibleEnums": "extensible-enums-swagger.json", + "Header": "header.json", + "Http": "httpInfrastructure.json", + "IncorrectErrorResponse": "incorrect-error-response.json", + "Report": "report.json", + "RequiredOptional": "required-optional.json", + "Url": "url.json", + "Validation": "validation.json", + "CustomBaseUri": "custom-baseUrl.json", + "CustomBaseUriMoreOptions": "custom-baseUrl-more-options.json", + "MergePatchJson": "merge-patch.json", + "ModelFlattening": "model-flattening.json", + "Xml": "xml-service.json", + "UrlMultiCollectionFormat": "url-multi-collectionFormat.json", + "XmsErrorResponse": "xms-error-responses.json", + "MediaTypes": "media_types.json", + "ObjectType": "object-type.json", + "NonStringEnums": "non-string-enum.json", + "MultipleInheritance": "multiple-inheritance.json", + "NoOperations": "no-operations.json", "ParameterizedEndpoint": "parameterized-endpoint.json", "ReservedWords": "reserved-words.json", "SecurityAadSwagger": "security-aad.json", @@ -96,56 +97,51 @@ class Config(NamedTuple): } _DPG_SWAGGER_MAPPINGS = { - 'DPGServiceDrivenInitial': 'dpg-initial.json', - 'DPGServiceDrivenUpdateOne': 'dpg-update1.json', - 'DPGCustomizationInitial': 'dpg-customization.json', - 'DPGCustomizationCustomized': 'dpg-customization.json', + "DPGServiceDrivenInitial": "dpg-initial.json", + "DPGServiceDrivenUpdateOne": "dpg-update1.json", + "DPGCustomizationInitial": "dpg-customization.json", + "DPGCustomizationCustomized": "dpg-customization.json", } _GENERATOR_SPECIFIC_TESTS = { _Generator.LEGACY: { _SwaggerGroup.VANILLA: { - 'BodyArrayWithNamespaceFolders': 'body-array.json', - 'BodyByteWithPackageName': 'body-byte.json', - 'SecurityAadSwaggerCredentialFlag': 'security-aad.json', - 'SecurityKeySwaggerCredentialFlag': 'security-key.json', + "BodyArrayWithNamespaceFolders": "body-array.json", + "BodyByteWithPackageName": "body-byte.json", + "SecurityAadSwaggerCredentialFlag": "security-aad.json", + "SecurityKeySwaggerCredentialFlag": "security-key.json", }, _SwaggerGroup.AZURE_ARM: { - 'HeadWithAzureKeyCredentialPolicy': 'head.json', - 'SecurityAadSwagger': 'security-aad.json', - 'SecurityKeySwagger': 'security-key.json', - } + "HeadWithAzureKeyCredentialPolicy": "head.json", + "SecurityAadSwagger": "security-aad.json", + "SecurityKeySwagger": "security-key.json", + }, }, _Generator.VERSION_TOLERANT: { _SwaggerGroup.DPG: { - 'DPGTestModels': 'dpg-customization.json', + "DPGTestModels": "dpg-customization.json", }, _SwaggerGroup.VANILLA: { - 'NoNamespaceFlag': "any-type.json", - } + "NoNamespaceFlag": "any-type.json", + }, }, } _PACKAGE_NAME_TO_OVERRIDE_FLAGS: Dict[str, Dict[str, Any]] = { - 'DPGTestModels': { + "DPGTestModels": { "models-mode": "msrest", }, - 'ClientEnum': { + "ClientEnum": { "models-mode": "msrest", }, - 'Xml': { + "Xml": { "models-mode": "msrest", }, - 'BodyArrayWithNamespaceFolders': { - "namespace": "vanilla.body.array" - }, - "BodyByteWithPackageName": { - "package-name": "packagename", - "override-client-name": "class_name" - }, + "BodyArrayWithNamespaceFolders": {"namespace": "vanilla.body.array"}, + "BodyByteWithPackageName": {"package-name": "packagename", "override-client-name": "class_name"}, "HeadWithAzureKeyCredentialPolicy": { "credential-default-policy-type": "AzureKeyCredentialPolicy", - "credential-key-header-name": "Authorization" + "credential-key-header-name": "Authorization", }, "SecurityAadSwaggerCredentialFlag": { "add-credential": True, @@ -156,56 +152,53 @@ class Config(NamedTuple): "add-credential": True, "title": "SecurityKeySwaggerCredentialFlag", }, - "NoNamespaceFlag": { - "namespace": None, # clear our namespace flag - "package-name": "nonamespaceflag" - } + "NoNamespaceFlag": {"namespace": None, "package-name": "nonamespaceflag"}, # clear our namespace flag } _AZURE_SWAGGER_MAPPINGS = { - 'AzureBodyDuration': 'body-duration.json', - 'AzureReport': 'azure-report.json', - 'AzureParameterGrouping': 'azure-parameter-grouping.json', - 'CustomBaseUri': 'custom-baseUrl.json', - 'LroWithParameterizedEndpoints': 'lro-parameterized-endpoints.json', - 'Paging': 'paging.json', - 'CustomUrlPaging': 'custom-baseUrl-paging.json', + "AzureBodyDuration": "body-duration.json", + "AzureReport": "azure-report.json", + "AzureParameterGrouping": "azure-parameter-grouping.json", + "CustomBaseUri": "custom-baseUrl.json", + "LroWithParameterizedEndpoints": "lro-parameterized-endpoints.json", + "Paging": "paging.json", + "CustomUrlPaging": "custom-baseUrl-paging.json", } # The list is mostly built on Swaggers that uses CloudError feature # These Swagger should be modified to test their features, and not the CloudError one _AZURE_ARM_SWAGGER_MAPPINGS = { - 'Head': 'head.json', - 'HeadExceptions': 'head-exceptions.json', - 'StorageManagementClient': 'storage.json', - 'Lro': 'lro.json', - 'SubscriptionIdApiVersion': 'subscriptionId-apiVersion.json', - 'AzureSpecials': 'azure-special-properties.json', + "Head": "head.json", + "HeadExceptions": "head-exceptions.json", + "StorageManagementClient": "storage.json", + "Lro": "lro.json", + "SubscriptionIdApiVersion": "subscriptionId-apiVersion.json", + "AzureSpecials": "azure-special-properties.json", } """Overwrite default behavior we have assigned to test flags """ _OVERWRITE_DEFAULT_NAMESPACE = { - 'ExtensibleEnums': 'extensibleenumsswagger', - 'Http': 'httpinfrastructure', - 'CustomBaseUri': 'custombaseurl', - 'CustomBaseUriMoreOptions': 'custombaseurlmoreoptions', - 'Xml': 'xmlservice', - 'AzureBodyDuration': 'bodyduration', - 'CustomUrlPaging': 'custombaseurlpaging', - 'AzureSpecials': 'azurespecialproperties', - 'StorageManagementClient': 'storage', + "ExtensibleEnums": "extensibleenumsswagger", + "Http": "httpinfrastructure", + "CustomBaseUri": "custombaseurl", + "CustomBaseUriMoreOptions": "custombaseurlmoreoptions", + "Xml": "xmlservice", + "AzureBodyDuration": "bodyduration", + "CustomUrlPaging": "custombaseurlpaging", + "AzureSpecials": "azurespecialproperties", + "StorageManagementClient": "storage", } _PACKAGES_WITH_CLIENT_SIDE_VALIDATION = [ - 'Validation', - 'Url', - 'RequiredOptional', - 'CustomBaseUri', - 'BodyComplex', - 'AzureParameterGrouping', - 'AzureSpecials' + "Validation", + "Url", + "RequiredOptional", + "CustomBaseUri", + "BodyComplex", + "AzureParameterGrouping", + "AzureSpecials", ] _POSTPROCESS_PACKAGES = [ @@ -215,9 +208,7 @@ class Config(NamedTuple): ] -def _get_config( - swagger_group: _SwaggerGroup, package_name: str, **kwargs -) -> Config: +def _get_config(swagger_group: _SwaggerGroup, package_name: str, **kwargs) -> Config: if swagger_group == _SwaggerGroup.VANILLA: generation_section = "vanilla" elif swagger_group == _SwaggerGroup.DPG: @@ -243,19 +234,16 @@ def _build_flags( debug: bool, swagger_group: _SwaggerGroup, override_flags: Optional[Dict[str, Any]] = None, - **kwargs + **kwargs, ) -> Dict[str, Any]: testserver_dir = "node_modules/@microsoft.azure/autorest.testserver/swagger" override_flags = override_flags or {} - override_flags.update( - _PACKAGE_NAME_TO_OVERRIDE_FLAGS.get(package_name, {})) + override_flags.update(_PACKAGE_NAME_TO_OVERRIDE_FLAGS.get(package_name, {})) version_tolerant = kwargs.get("version_tolerant", False) client_side_validation = package_name in _PACKAGES_WITH_CLIENT_SIDE_VALIDATION and not version_tolerant - namespace = kwargs.pop("namespace", _OVERWRITE_DEFAULT_NAMESPACE.get( - package_name, package_name.lower())) + namespace = kwargs.pop("namespace", _OVERWRITE_DEFAULT_NAMESPACE.get(package_name, package_name.lower())) - generator, output_folder = _get_config( - swagger_group, package_name, **kwargs) + generator, output_folder = _get_config(swagger_group, package_name, **kwargs) if generator == _Generator.LEGACY: override_flags["payload-flattening-threshold"] = 1 @@ -303,11 +291,8 @@ def _build_command_line( # package name, so we override package names override_flags = override_flags or {} override_flags.update({"package-name": package_name.lower()}) - flags = _build_flags(package_name, swagger_name, debug, - swagger_group, override_flags, **kwargs) - flag_strings = [ - f"--{flag}={value}" for flag, value in flags.items() - ] + flags = _build_flags(package_name, swagger_name, debug, swagger_group, override_flags, **kwargs) + flag_strings = [f"--{flag}={value}" for flag, value in flags.items()] debug_str = " --python.debugger" if debug else "" return "autorest " + M4_VERSION + " ".join(flag_strings) + debug_str @@ -329,8 +314,7 @@ def _run_single_autorest(cmd_line, debug=False): if result.ok or result.return_code is None: print(Fore.GREEN + f'Call "{cmd_line}" done with success') return True - print(Fore.RED + - f'Call "{cmd_line}" failed with {result.return_code}\n{result.stdout}\n{result.stderr}') + print(Fore.RED + f'Call "{cmd_line}" failed with {result.return_code}\n{result.stdout}\n{result.stderr}') try: output_folder = re.findall(r"--output-folder=([^\s]+)", cmd_line)[0] @@ -345,23 +329,21 @@ def _regenerate( debug: bool, swagger_group: _SwaggerGroup, override_flags: Optional[Dict[str, Any]] = None, - **kwargs + **kwargs, ) -> None: cmds = [] post_process_cmds = [] for package_name, swagger_name in mapping.items(): - command_line = _build_command_line( - package_name, swagger_name, debug, swagger_group, override_flags, **kwargs) + command_line = _build_command_line(package_name, swagger_name, debug, swagger_group, override_flags, **kwargs) - print(Fore.YELLOW + f'Queuing up: {command_line}') + print(Fore.YELLOW + f"Queuing up: {command_line}") cmds.append(command_line) if kwargs.get("version_tolerant") and package_name in _POSTPROCESS_PACKAGES: config = _get_config(swagger_group, package_name, **kwargs) post_process_cmd = f"autorest --use={AUTOREST_DIR} --postprocess --output-folder={config.output_folder}" if debug: post_process_cmd += " --python.debugger" - print(Fore.YELLOW + - f'Queuing up post process command: {post_process_cmd}') + print(Fore.YELLOW + f"Queuing up post process command: {post_process_cmd}") post_process_cmds.append(post_process_cmd) _run_autorest(cmds, debug=debug) _run_autorest(post_process_cmds, debug=debug) @@ -373,11 +355,9 @@ def _prepare_mapping_and_regenerate(c, mapping, swagger_group, swagger_name=None else: generator = _Generator.LEGACY mapping_copy = copy.copy(mapping) - mapping_copy.update(_GENERATOR_SPECIFIC_TESTS.get( - generator, {}).get(swagger_group, {})) + mapping_copy.update(_GENERATOR_SPECIFIC_TESTS.get(generator, {}).get(swagger_group, {})) if swagger_name: - prepared_mapping = {k: v for k, v in mapping_copy.items( - ) if swagger_name.lower() in k.lower()} + prepared_mapping = {k: v for k, v in mapping_copy.items() if swagger_name.lower() in k.lower()} else: prepared_mapping = mapping_copy _regenerate(prepared_mapping, debug, swagger_group=swagger_group, **kwargs) @@ -385,8 +365,7 @@ def _prepare_mapping_and_regenerate(c, mapping, swagger_group, swagger_name=None @task def regenerate_vanilla_legacy(c, swagger_name=None, debug=False, **kwargs): - _prepare_mapping_and_regenerate( - c, _VANILLA_SWAGGER_MAPPINGS, _SwaggerGroup.VANILLA, swagger_name, debug, **kwargs) + _prepare_mapping_and_regenerate(c, _VANILLA_SWAGGER_MAPPINGS, _SwaggerGroup.VANILLA, swagger_name, debug, **kwargs) if not swagger_name: regenerate_package_mode(c, swagger_group=_SwaggerGroup.VANILLA) @@ -394,33 +373,20 @@ def regenerate_vanilla_legacy(c, swagger_name=None, debug=False, **kwargs): @task def regenerate_dpg_version_tolerant(c, swagger_name=None, debug=False, **kwargs): _prepare_mapping_and_regenerate( - c, - _DPG_SWAGGER_MAPPINGS, - _SwaggerGroup.DPG, - swagger_name, - debug, - version_tolerant=True, - **kwargs + c, _DPG_SWAGGER_MAPPINGS, _SwaggerGroup.DPG, swagger_name, debug, version_tolerant=True, **kwargs ) @task def regenerate_vanilla_version_tolerant(c, swagger_name=None, debug=False, **kwargs): _prepare_mapping_and_regenerate( - c, - _VANILLA_SWAGGER_MAPPINGS, - _SwaggerGroup.VANILLA, - swagger_name, - debug, - version_tolerant=True, - **kwargs + c, _VANILLA_SWAGGER_MAPPINGS, _SwaggerGroup.VANILLA, swagger_name, debug, version_tolerant=True, **kwargs ) @task def regenerate_azure_legacy(c, swagger_name=None, debug=False, **kwargs): - _prepare_mapping_and_regenerate( - c, _AZURE_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE, swagger_name, debug, **kwargs) + _prepare_mapping_and_regenerate(c, _AZURE_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE, swagger_name, debug, **kwargs) if not swagger_name: regenerate_custom_poller_pager_legacy(c, debug) regenerate_package_mode(c, swagger_group=_SwaggerGroup.AZURE) @@ -430,7 +396,8 @@ def regenerate_azure_legacy(c, swagger_name=None, debug=False, **kwargs): @task def regenerate_azure_version_tolerant(c, swagger_name=None, debug=False, **kwargs): _prepare_mapping_and_regenerate( - c, _AZURE_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE, swagger_name, debug, version_tolerant=True, **kwargs) + c, _AZURE_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE, swagger_name, debug, version_tolerant=True, **kwargs + ) if not swagger_name: regenerate_custom_poller_pager_version_tolerant(c, debug) regenerate_lro_paging_version_tolerant(c, debug) @@ -439,12 +406,15 @@ def regenerate_azure_version_tolerant(c, swagger_name=None, debug=False, **kwarg @task def regenerate_azure_arm_legacy(c, swagger_name=None, debug=False, **kwargs): _prepare_mapping_and_regenerate( - c, _AZURE_ARM_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE_ARM, swagger_name, debug, **kwargs) + c, _AZURE_ARM_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE_ARM, swagger_name, debug, **kwargs + ) @task def regenerate_azure_arm_version_tolerant(c, swagger_name=None, debug=False, **kwargs): - return _prepare_mapping_and_regenerate(c, _AZURE_ARM_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE_ARM, swagger_name, debug, version_tolerant=True, **kwargs) + return _prepare_mapping_and_regenerate( + c, _AZURE_ARM_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE_ARM, swagger_name, debug, version_tolerant=True, **kwargs + ) @task @@ -468,11 +438,10 @@ def regenerate( vanilla=False, azure=False, azure_arm=False, - dpg=False + dpg=False, ): if legacy and dpg: - raise ValueError( - "Can not specify legacy flag and dpg flag at the same time.") + raise ValueError("Can not specify legacy flag and dpg flag at the same time.") generators = [ "version_tolerant" if version_tolerant else "", "legacy" if legacy else "", @@ -501,21 +470,21 @@ def regenerate( ("version_tolerant", "azure_arm"): regenerate_azure_arm_version_tolerant, ("version_tolerant", "dpg"): regenerate_dpg_version_tolerant, } - funcs = [ - v for k, v in mapping.items() if k in itertools.product(generators, folder_flags) - ] + funcs = [v for k, v in mapping.items() if k in itertools.product(generators, folder_flags)] for func in funcs: func(c, swagger_name, debug) regenerate_unittests(c) + @task def regenerate_unittests(c): shutil.copyfile( "test/azure/legacy/Expected/AcceptanceTests/AzureBodyDuration/bodyduration/_serialization.py", - "test/unittests/storage_models/serialization.py" + "test/unittests/storage_models/serialization.py", ) + @task def regenerate_version_tolerant(c, swagger_name=None, debug=False): regenerate_dpg_version_tolerant(c, swagger_name, debug) @@ -528,7 +497,7 @@ def regenerate_version_tolerant(c, swagger_name=None, debug=False): def test(c): # run language-specific tests base_dir = os.path.dirname(__file__) - cmd = 'tox run -e ci' + cmd = "tox run -e ci" autorest_types = ["azure", "vanilla"] gen_types = ["legacy", "version-tolerant"] @@ -544,8 +513,8 @@ def test(c): def _multiapi_command_line(location, debug): cwd = os.getcwd() cmd = ( - f'autorest {M4_VERSION} {location} --use=. --multiapi --output-artifact=code-model-v4-no-tags ' + - f'--python-sdks-folder={cwd}/test/' + f"autorest {M4_VERSION} {location} --use=. --multiapi --output-artifact=code-model-v4-no-tags " + + f"--python-sdks-folder={cwd}/test/" ) if debug: cmd += " --python.debugger" @@ -576,25 +545,25 @@ def regenerate_multiapi(c, debug=False, swagger_name="test"): "test/multiapi/specification/multiapicombiner/README.md", ] - cmds = [_multiapi_command_line( - spec, debug) for spec in available_specifications if swagger_name.lower() in spec] + cmds = [_multiapi_command_line(spec, debug) for spec in available_specifications if swagger_name.lower() in spec] _run_autorest(cmds, debug) check_call(f"python {Path('test/multiapi/run_multiapi_combiner.py')} multiapicombiner", shell=True) + @task def regenerate_package_mode(c, debug=False, swagger_group=None): cwd = os.getcwd() azure_packages = [ - 'test/azure/legacy/specification/packagemodemgmtplane/README.md', - 'test/azure/legacy/specification/packagemodecustomize/README.md', - 'test/azure/legacy/specification/packagemodedataplane/README.md', - 'test/azure/legacy/specification/packagemodebatch/README.md', + "test/azure/legacy/specification/packagemodemgmtplane/README.md", + "test/azure/legacy/specification/packagemodecustomize/README.md", + "test/azure/legacy/specification/packagemodedataplane/README.md", + "test/azure/legacy/specification/packagemodebatch/README.md", ] vanilla_packages = [ - 'test/vanilla/legacy/specification/packagemodedataplane/README.md', - 'test/vanilla/legacy/specification/internaloperation/README.md', + "test/vanilla/legacy/specification/packagemodedataplane/README.md", + "test/vanilla/legacy/specification/internaloperation/README.md", ] if swagger_group == _SwaggerGroup.VANILLA: package_mode = vanilla_packages @@ -602,9 +571,7 @@ def regenerate_package_mode(c, debug=False, swagger_group=None): package_mode = azure_packages else: package_mode = azure_packages + vanilla_packages - cmds = [ - f'autorest {M4_VERSION} {readme} --use=. --python-sdks-folder={cwd}/test/' for readme in package_mode - ] + cmds = [f"autorest {M4_VERSION} {readme} --use=. --python-sdks-folder={cwd}/test/" for readme in package_mode] _run_autorest(cmds, debug=debug) @@ -612,46 +579,37 @@ def regenerate_package_mode(c, debug=False, swagger_group=None): @task def regenerate_custom_poller_pager_legacy(c, debug=False): cwd = os.getcwd() - cmd = ( - f'autorest {M4_VERSION} test/azure/legacy/specification/custompollerpager/README.md --use=. --python-sdks-folder={cwd}/test/' - ) + cmd = f"autorest {M4_VERSION} test/azure/legacy/specification/custompollerpager/README.md --use=. --python-sdks-folder={cwd}/test/" _run_autorest([cmd], debug=debug) @task def regenerate_mixed_api_version_legacy(c, debug=False): cwd = os.getcwd() - cmd = ( - f'autorest {M4_VERSION} test/azure/legacy/specification/mixedapiversion/README.md --use=. --python-sdks-folder={cwd}/test/' - ) + cmd = f"autorest {M4_VERSION} test/azure/legacy/specification/mixedapiversion/README.md --use=. --python-sdks-folder={cwd}/test/" _run_autorest([cmd], debug=debug) @task def regenerate_custom_poller_pager_version_tolerant(c, debug=False): cwd = os.getcwd() - cmd = ( - f'autorest {M4_VERSION} test/azure/version-tolerant/specification/custompollerpager/README.md --use=. --python-sdks-folder={cwd}/test/' - ) + cmd = f"autorest {M4_VERSION} test/azure/version-tolerant/specification/custompollerpager/README.md --use=. --python-sdks-folder={cwd}/test/" _run_autorest([cmd], debug=debug) + @task def regenerate_lro_paging_version_tolerant(c, debug=False): cwd = os.getcwd() - cmd = ( - f'autorest {M4_VERSION} test/azure/version-tolerant/specification/lropaging/README.md --use=. --python-sdks-folder={cwd}/test/' - ) + cmd = f"autorest {M4_VERSION} test/azure/version-tolerant/specification/lropaging/README.md --use=. --python-sdks-folder={cwd}/test/" _run_autorest([cmd], debug=debug) + @task def regenerate_samples(c, debug=False): cwd = os.getcwd() sample_to_special_flags = { "management": None, - "multiapi": { - "multiapi": True, - "python-sdks-folder": f'{cwd}/samples/specification/multiapi' - }, + "multiapi": {"multiapi": True, "python-sdks-folder": f"{cwd}/samples/specification/multiapi"}, "azure_key_credential": None, "directives": None, "basic": None, @@ -659,11 +617,9 @@ def regenerate_samples(c, debug=False): cmds = [] for sample, special_flags in sample_to_special_flags.items(): - cmd = f'autorest {M4_VERSION} samples/specification/{sample}/readme.md --use=. ' + cmd = f"autorest {M4_VERSION} samples/specification/{sample}/readme.md --use=. " if special_flags: - flag_strings = [ - f"--{flag}={value}" for flag, value in special_flags.items() - ] + flag_strings = [f"--{flag}={value}" for flag, value in special_flags.items()] cmd += " ".join(flag_strings) cmds.append(cmd) _run_autorest(cmds, debug) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_azure_url.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_azure_url.py index e5c90a72b8e..0c91d91735d 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_azure_url.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_azure_url.py @@ -38,8 +38,10 @@ async def test_azure_url(self, credential, authentication_policy): sub_id = str(uuid4()) - async with MicrosoftAzureTestUrl(credential, sub_id, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + async with MicrosoftAzureTestUrl( + credential, sub_id, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: group = await client.group.get_sample_resource_group("testgoup101") - assert group.name == "testgroup101" - assert group.location == "West US" + assert group.name == "testgroup101" + assert group.location == "West US" diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_config.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_config.py index d0cb5c8fc4b..ef5d64ee7fe 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_config.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_config.py @@ -25,38 +25,48 @@ # -------------------------------------------------------------------------- import pytest from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy + # Head is azure-arm from head.aio import AutoRestHeadTestService + class TestConfig(object): @pytest.mark.asyncio async def test_arm_http_logging_policy_default(self, credential): async with AutoRestHeadTestService(credential, base_url="http://localhost:3000") as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) @pytest.mark.asyncio async def test_arm_http_logging_policy_custom(self, credential): http_logging_policy = ARMHttpLoggingPolicy(base_url="test") http_logging_policy = ARMHttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) - async with AutoRestHeadTestService(credential, base_url="http://localhost:3000", http_logging_policy=http_logging_policy) as client: + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) + async with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", http_logging_policy=http_logging_policy + ) as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) @pytest.mark.asyncio async def test_credential_scopes_default(self, credential): async with AutoRestHeadTestService(credential) as client: - assert client._config.credential_scopes == ['https://management.azure.com/.default'] + assert client._config.credential_scopes == ["https://management.azure.com/.default"] @pytest.mark.asyncio async def test_credential_scopes_override(self, credential): - async with AutoRestHeadTestService(credential, credential_scopes=["http://i-should-be-the-only-credential"]) as client: + async with AutoRestHeadTestService( + credential, credential_scopes=["http://i-should-be-the-only-credential"] + ) as client: assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] @pytest.mark.asyncio async def test_arm_authentication_policy_default(self, credential): async with AutoRestHeadTestService(credential, base_url="http://localhost:3000") as client: - assert isinstance(client._config.authentication_policy, AsyncARMChallengeAuthenticationPolicy) \ No newline at end of file + assert isinstance(client._config.authentication_policy, AsyncARMChallengeAuthenticationPolicy) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_custom_poller_pager.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_custom_poller_pager.py index 21ee2958f57..ccc54b1f95f 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_custom_poller_pager.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_custom_poller_pager.py @@ -29,18 +29,24 @@ import pytest + @pytest.fixture @async_generator async def client(credential, authentication_policy): - async with AutoRestPagingTestService(credential, host="host:3000", authentication_policy=authentication_policy) as client: + async with AutoRestPagingTestService( + credential, host="host:3000", authentication_policy=authentication_policy + ) as client: await yield_(client) @pytest.fixture def custom_url_client(credential, authentication_policy): - with AutoRestParameterizedHostTestPagingClient(credential, host="host:3000", authentication_policy=authentication_policy) as client: + with AutoRestParameterizedHostTestPagingClient( + credential, host="host:3000", authentication_policy=authentication_policy + ) as client: yield client + class TestPaging(object): def test_custom_pager(self, client): pager = client.paging.get_single_pages() @@ -49,4 +55,4 @@ def test_custom_pager(self, client): @pytest.mark.asyncio async def test_custom_poller(self, client): poller = await client.paging.begin_get_multiple_pages_lro() - assert isinstance(poller, AsyncCustomPoller) \ No newline at end of file + assert isinstance(poller, AsyncCustomPoller) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_duration.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_duration.py index 3139a20f103..aafe2dad955 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_duration.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_duration.py @@ -39,6 +39,7 @@ async def client(): async with AutoRestDurationTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestDuration(object): @pytest.mark.asyncio @@ -53,4 +54,3 @@ async def test_positive_duration(self, client): await client.duration.get_positive_duration() delta = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) await client.duration.put_positive_duration(delta) - diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_head.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_head.py index e5e2cc119c1..9bd5834b867 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_head.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_head.py @@ -42,12 +42,15 @@ import pytest + class TestHead(object): @pytest.mark.asyncio async def test_head(self, credential, authentication_policy): - async with AutoRestHeadTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + async with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: assert await client.http_success.head200() assert await client.http_success.head204() @@ -56,7 +59,9 @@ async def test_head(self, credential, authentication_policy): @pytest.mark.asyncio async def test_head_exception(self, credential, authentication_policy): - async with AutoRestHeadExceptionTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + async with AutoRestHeadExceptionTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: await client.head_exception.head200() await client.head_exception.head204() diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro.py index 83bb551644b..183605582ef 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro.py @@ -55,6 +55,7 @@ POLLING_INTERVAL = 0 + class AutorestTestARMPolling(AsyncARMPolling): def _polling_cookie(self, response): @@ -65,30 +66,27 @@ def _polling_cookie(self, response): otherwise an empty dictionary. """ parsed_url = urlparse(response.request.url) - host = parsed_url.hostname.strip('.') - if host == 'localhost': - return {'cookie': response.headers.get('set-cookie', '')} + host = parsed_url.hostname.strip(".") + if host == "localhost": + return {"cookie": response.headers.get("set-cookie", "")} return {} async def request_status(self, status_link): request = self._client.get(status_link, headers=self._polling_cookie(self._pipeline_response.http_response)) # ARM requires to re-inject 'x-ms-client-request-id' while polling - if 'request_id' not in self._operation_config: - self._operation_config['request_id'] = self._get_request_id() - return (await self._client._pipeline.run(request, stream=False, **self._operation_config)) + if "request_id" not in self._operation_config: + self._operation_config["request_id"] = self._get_request_id() + return await self._client._pipeline.run(request, stream=False, **self._operation_config) + @pytest.fixture @async_generator async def client(cookie_policy, credential): """Create a AutoRestLongRunningOperationTestService client with test server credentials.""" - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] - async with AutoRestLongRunningOperationTestService(credential, base_url="http://localhost:3000", policies=policies, polling_interval=POLLING_INTERVAL) as client: + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), AsyncRetryPolicy(), cookie_policy] + async with AutoRestLongRunningOperationTestService( + credential, base_url="http://localhost:3000", policies=policies, polling_interval=POLLING_INTERVAL + ) as client: await yield_(client) @@ -96,9 +94,10 @@ async def client(cookie_policy, credential): def product(): return Product(location="West US") + @pytest.fixture() def custom_headers(): - return {"x-ms-client-request-id": '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'} + return {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} class TestLro: @@ -109,7 +108,7 @@ async def assert_raises_with_message(self, msg, func, *args, **kwargs): except HttpResponseError as err: assert err.response is not None - print("BODY: "+err.response.text()) + print("BODY: " + err.response.text()) try: msg, internal_msg = msg @@ -161,7 +160,9 @@ async def test_happy_put201_creating_succeeded200(self, client, product): async def test_happy_put201_creating_failed200(self, client, product): await self.assert_raises_with_message( ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put201_creating_failed200, product) + client.lros.begin_put201_creating_failed200, + product, + ) process = await self.lro_result(client.lros.begin_put201_creating_failed200, product, polling=False) assert "Created" == process.provisioning_state @@ -178,7 +179,9 @@ async def test_happy_put200_updating_succeeded204(self, client, product): async def test_happy_put200_acceptedcanceled200(self, client, product): await self.assert_raises_with_message( ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put200_acceptedcanceled200, product) + client.lros.begin_put200_acceptedcanceled200, + product, + ) process = await self.lro_result(client.lros.begin_put200_acceptedcanceled200, product, polling=False) assert "Accepted" == process.provisioning_state @@ -239,12 +242,14 @@ async def test_happy_put_retry_succeeded(self, client, product): @pytest.mark.asyncio async def test_happy_put_retry_failed_canceled(self, client, product): await self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put_async_retry_failed, product) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_put_async_retry_failed, product + ) await self.assert_raises_with_message( ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put_async_no_retrycanceled, product) + client.lros.begin_put_async_no_retrycanceled, + product, + ) @pytest.mark.asyncio async def test_post202_retry200(self, client, product): @@ -265,12 +270,12 @@ async def test_happy_delete_no_header_in_retry(self, client): @pytest.mark.asyncio async def test_happy_delete_async_retry_failed_canceled(self, client): await self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_delete_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_delete_async_retrycanceled + ) await self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_delete_async_retry_failed) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_delete_async_retry_failed + ) @pytest.mark.asyncio async def test_happy_delete_async_succeeded(self, client): @@ -283,26 +288,25 @@ async def test_happy_delete_provisioning(self, client): assert "Succeeded" == process.provisioning_state result = await self.lro_result(client.lros.begin_delete_provisioning202_deletingcanceled200) - assert result.provisioning_state == 'Canceled' + assert result.provisioning_state == "Canceled" result = await self.lro_result(client.lros.begin_delete_provisioning202_deleting_failed200) - assert result.provisioning_state == 'Failed' + assert result.provisioning_state == "Failed" @pytest.mark.asyncio async def test_happy_post(self, client, product): assert await self.lro_result(client.lros.begin_post202_no_retry204, product) is None sku = await self.lro_result(client.lros.begin_post200_with_payload) - assert sku.id == '1' + assert sku.id == "1" @pytest.mark.asyncio async def test_happy_post_async_retry_failed_canceled(self, client, product): - await self.assert_raises_with_message("Internal Server Error", - client.lros.begin_post_async_retry_failed) + await self.assert_raises_with_message("Internal Server Error", client.lros.begin_post_async_retry_failed) await self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_post_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_post_async_retrycanceled + ) @pytest.mark.asyncio async def test_happy_post_async_succeeded(self, client, product): @@ -315,15 +319,15 @@ async def test_happy_post_async_succeeded(self, client, product): @pytest.mark.asyncio async def test_retrys_put(self, client, product): process = await self.lro_result(client.lro_retrys.begin_put201_creating_succeeded200, product) - assert 'Succeeded' == process.provisioning_state + assert "Succeeded" == process.provisioning_state process = await self.lro_result(client.lro_retrys.begin_put_async_relative_retry_succeeded, product) - assert 'Succeeded' == process.provisioning_state + assert "Succeeded" == process.provisioning_state @pytest.mark.asyncio async def test_retrys_delete(self, client, product): process = await self.lro_result(client.lro_retrys.begin_delete_provisioning202_accepted200_succeeded) - assert 'Succeeded' == process.provisioning_state + assert "Succeeded" == process.provisioning_state assert await self.lro_result(client.lro_retrys.begin_delete202_retry200) is None assert await self.lro_result(client.lro_retrys.begin_delete_async_relative_retry_succeeded) is None @@ -335,47 +339,65 @@ async def test_retrys_post(self, client, product): @pytest.mark.asyncio async def test_custom_headers_put_async_retry_succeeded(self, client, product, custom_headers): - process = await self.lro_result(client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers) + process = await self.lro_result( + client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers + ) assert process is not None @pytest.mark.asyncio async def test_custom_headers_post_async_retry_succeeded(self, client, product, custom_headers): - process = await self.lro_result(client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers) + process = await self.lro_result( + client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers + ) assert process is None @pytest.mark.asyncio async def test_custom_headers_put201_creating_succeeded200(self, client, product, custom_headers): - process = await self.lro_result(client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers) + process = await self.lro_result( + client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers + ) assert process is not None @pytest.mark.asyncio async def test_custom_headers_post202_retry200(self, client, product, custom_headers): - process = await self.lro_result(client.lr_os_custom_header.begin_post202_retry200, product, headers=custom_headers) + process = await self.lro_result( + client.lr_os_custom_header.begin_post202_retry200, product, headers=custom_headers + ) assert process is None @pytest.mark.asyncio async def test_sads_put_non_retry(self, client, product): - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_put_non_retry400, product) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_put_non_retry400, product) - await self.assert_raises_with_message("Error from the server", - client.lrosads.begin_put_non_retry201_creating400, product) + await self.assert_raises_with_message( + "Error from the server", client.lrosads.begin_put_non_retry201_creating400, product + ) @pytest.mark.asyncio async def test_sads_put_async_relative(self, client, product): - await self.assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.lrosads.begin_put_async_relative_retry400, product) + await self.assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", + client.lrosads.begin_put_async_relative_retry400, + product, + ) - await self.assert_raises_with_message("no status found in body", - client.lrosads.begin_put_async_relative_retry_no_status, product) + await self.assert_raises_with_message( + "no status found in body", client.lrosads.begin_put_async_relative_retry_no_status, product + ) - await self.assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_async_relative_retry_no_status_payload, product) + await self.assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_async_relative_retry_no_status_payload, + product, + ) @pytest.mark.asyncio async def test_sads_put_error201_no_provisioning_state_payload(self, client, product): - await self.assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_error201_no_provisioning_state_payload, product) + await self.assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_error201_no_provisioning_state_payload, + product, + ) @pytest.mark.asyncio async def test_sads_put200_invalid_json_with_exception(self, client, product): @@ -398,19 +420,17 @@ async def test_sads_put_non_retry201_creating400_invalid_json_with_exception(sel @pytest.mark.asyncio async def tests_lro_sads_delete_non_retry(self, client, product): - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_non_retry400) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_delete_non_retry400) - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_delete202_non_retry400) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_delete202_non_retry400) @pytest.mark.asyncio async def test_sads_delete_async_relative(self, client, product): - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_async_relative_retry400) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_delete_async_relative_retry400) - await self.assert_raises_with_message("no status found in body", - client.lrosads.begin_delete_async_relative_retry_no_status) + await self.assert_raises_with_message( + "no status found in body", client.lrosads.begin_delete_async_relative_retry_no_status + ) @pytest.mark.asyncio async def test_sads_delete204_succeeded(self, client): @@ -431,19 +451,18 @@ async def test_sads_delete202_retry_invalid_header_with_exception(self, client): @pytest.mark.asyncio async def test_sads_post_non_retry(self, client, product): - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_post_non_retry400, product) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_post_non_retry400, product) - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_post202_non_retry400, product) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_post202_non_retry400, product) @pytest.mark.asyncio async def test_sads_post_async_relative(self, client, product): - await self.assert_raises_with_message("Bad Request", - client.lrosads.begin_post_async_relative_retry400, product) + await self.assert_raises_with_message("Bad Request", client.lrosads.begin_post_async_relative_retry400, product) - await self.assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_post_async_relative_retry_no_payload) + await self.assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_post_async_relative_retry_no_payload, + ) @pytest.mark.asyncio async def test_sads_post202_no_location(self, client): @@ -464,7 +483,7 @@ async def test_sads_post_async_relative_with_exception(self, client): @pytest.mark.asyncio async def test_post202_retry_invalid_header_with_exception(self, client): with pytest.raises(Exception): - await self.lro_result(client.lrosads.begin_post202_retry_invalid_header) + await self.lro_result(client.lrosads.begin_post202_retry_invalid_header) @pytest.mark.asyncio async def test_polling_interval_operation(self, client): @@ -491,14 +510,10 @@ async def test_polling_interval_config(self, cookie_policy, credential, client): assert abs(default_polling_interval_duration - 0) < 3 # Now we create a new client with a polling_interval of 1 - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] - client_one_second = AutoRestLongRunningOperationTestService(credential, base_url="http://localhost:3000", policies=policies, polling_interval=1) + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), AsyncRetryPolicy(), cookie_policy] + client_one_second = AutoRestLongRunningOperationTestService( + credential, base_url="http://localhost:3000", policies=policies, polling_interval=1 + ) one_second_polling_interval_start_time = time.time() poller = await client_one_second.lros.begin_post_double_headers_final_azure_header_get_default() product2 = await poller.result() diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py index 9bcfe63ad9a..9b17cbb2a97 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py @@ -27,18 +27,21 @@ from lrowithparameterizedendpoints.aio import LROWithParamaterizedEndpoints from async_generator import yield_, async_generator + @pytest.fixture @async_generator async def client(credential): async with LROWithParamaterizedEndpoints(credential=credential, host="host:3000") as client: await yield_(client) + @pytest.mark.asyncio async def test_poll_with_parameterized_endpoints(client): - poller = await client.begin_poll_with_parameterized_endpoints(account_name='local', polling_interval=0) - assert (await poller.result()) == 'success' + poller = await client.begin_poll_with_parameterized_endpoints(account_name="local", polling_interval=0) + assert (await poller.result()) == "success" + @pytest.mark.asyncio async def test_poll_with_constant_parameterized_endpoints(client): - poller = await client.begin_poll_with_constant_parameterized_endpoints(account_name='local', polling_interval=0) - assert (await poller.result()) == 'success' + poller = await client.begin_poll_with_constant_parameterized_endpoints(account_name="local", polling_interval=0) + assert (await poller.result()) == "success" diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_paging.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_paging.py index 41a27ce0bd1..52c7dae5e86 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_paging.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_paging.py @@ -44,25 +44,22 @@ import pytest + @pytest.fixture @async_generator async def client(cookie_policy): - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), AsyncRetryPolicy(), cookie_policy] async with AutoRestPagingTestService(base_url="http://localhost:3000", policies=policies) as client: await yield_(client) + @pytest.fixture @async_generator async def custom_url_client(): async with AutoRestParameterizedHostTestPagingClient(host="host:3000") as client: await yield_(client) + class TestPaging(object): @pytest.mark.asyncio async def test_get_no_item_name_pages(self, client): @@ -98,6 +95,7 @@ def cb(list_of_obj): for obj in list_of_obj: obj.marked = True return list_of_obj + async for obj in client.paging.get_single_pages(cls=cb): assert obj.marked @@ -131,7 +129,7 @@ async def test_get_multiple_pages(self, client): @pytest.mark.asyncio async def test_query_params(self, client): - pages = client.paging.get_with_query_params(required_query_parameter='100') + pages = client.paging.get_with_query_params(required_query_parameter="100") items = [] async for item in pages: items.append(item) @@ -164,6 +162,7 @@ async def test_get_multiple_pages_retry_second(self, client): @pytest.mark.asyncio async def test_get_multiple_pages_with_offset(self, client): from paging.models import PagingGetMultiplePagesWithOffsetOptions + options = PagingGetMultiplePagesWithOffsetOptions(offset=100) pages = client.paging.get_multiple_pages_with_offset(paging_get_multiple_pages_with_offset_options=options) items = [] @@ -230,9 +229,9 @@ async def test_custom_url_get_pages_partial_url_operation(self, custom_url_clien @pytest.mark.asyncio async def test_get_multiple_pages_lro(self, client): - """LRO + Paging at the same time. - """ + """LRO + Paging at the same time.""" from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + poller = await client.paging.begin_get_multiple_pages_lro(polling=AsyncARMPolling(timeout=0)) pager = await poller.result() items = [] diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_parameter.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_parameter.py index 2be00332e46..f1c2f8d7018 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_parameter.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_parameter.py @@ -33,15 +33,18 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestParameterGroupingTestService(base_url="http://localhost:3000") as client: await yield_(client) + @pytest.fixture def valid_subscription(): - return '1234-5678-9012-3456' + return "1234-5678-9012-3456" + @pytest.fixture @async_generator @@ -51,52 +54,67 @@ async def azure_client(valid_subscription, credential, authentication_policy): ) as client: await yield_(client) + @pytest.fixture def body_parameter(): return 1234 + @pytest.fixture def header_parameter(): - return 'header' + return "header" + @pytest.fixture def query_parameter(): return 21 + @pytest.fixture def path_parameter(): - return 'path' + return "path" @pytest.fixture def unencoded_path(): - return 'path1/path2/path3' + return "path1/path2/path3" + @pytest.fixture def unencoded_query(): - return 'value1&q2=value2&q3=value3' + return "value1&q2=value2&q3=value3" + class TestParameter(object): @pytest.mark.asyncio - async def test_post_all_required_parameters(self, client, body_parameter, header_parameter, query_parameter, path_parameter): + async def test_post_all_required_parameters( + self, client, body_parameter, header_parameter, query_parameter, path_parameter + ): from azureparametergrouping.models import ParameterGroupingPostRequiredParameters + # Valid required parameters - required_parameters = ParameterGroupingPostRequiredParameters(body=body_parameter, path=path_parameter, custom_header=header_parameter, query=query_parameter) + required_parameters = ParameterGroupingPostRequiredParameters( + body=body_parameter, path=path_parameter, custom_header=header_parameter, query=query_parameter + ) await client.parameter_grouping.post_required(required_parameters) @pytest.mark.asyncio async def test_post_required_parameters_null_optional_parameters(self, client, body_parameter, path_parameter): from azureparametergrouping.models import ParameterGroupingPostRequiredParameters - #Required parameters but null optional parameters - required_parameters = ParameterGroupingPostRequiredParameters(body=body_parameter, path=path_parameter, query=None) + + # Required parameters but null optional parameters + required_parameters = ParameterGroupingPostRequiredParameters( + body=body_parameter, path=path_parameter, query=None + ) await client.parameter_grouping.post_required(required_parameters) @pytest.mark.asyncio async def test_post_required_parameters_with_null_required_property(self, client, path_parameter): from azureparametergrouping.models import ParameterGroupingPostRequiredParameters - #Required parameters object is not null, but a required property of the object is - required_parameters = ParameterGroupingPostRequiredParameters(body = None, path = path_parameter) + + # Required parameters object is not null, but a required property of the object is + required_parameters = ParameterGroupingPostRequiredParameters(body=None, path=path_parameter) with pytest.raises(ValidationError): await client.parameter_grouping.post_required(required_parameters) @@ -105,47 +123,60 @@ async def test_post_required_parameters_with_null_required_property(self, client @pytest.mark.asyncio async def test_post_all_optional(self, client, header_parameter, query_parameter): - from azureparametergrouping.models import ParameterGroupingPostRequiredParameters, ParameterGroupingPostOptionalParameters - #Valid optional parameters - optional_parameters = ParameterGroupingPostOptionalParameters(custom_header = header_parameter, query = query_parameter) + from azureparametergrouping.models import ( + ParameterGroupingPostRequiredParameters, + ParameterGroupingPostOptionalParameters, + ) + + # Valid optional parameters + optional_parameters = ParameterGroupingPostOptionalParameters( + custom_header=header_parameter, query=query_parameter + ) await client.parameter_grouping.post_optional(optional_parameters) @pytest.mark.asyncio async def test_post_none_optional(self, client): - #null optional paramters + # null optional paramters await client.parameter_grouping.post_optional(None) @pytest.mark.asyncio async def test_post_all_multi_param_groups(self, client, header_parameter, query_parameter): - from azureparametergrouping.models import FirstParameterGroup, ParameterGroupingPostMultiParamGroupsSecondParamGroup - #Multiple grouped parameters - first_group = FirstParameterGroup(header_one = header_parameter, query_one = query_parameter) - second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(header_two = "header2", query_two = 42) + from azureparametergrouping.models import ( + FirstParameterGroup, + ParameterGroupingPostMultiParamGroupsSecondParamGroup, + ) + + # Multiple grouped parameters + first_group = FirstParameterGroup(header_one=header_parameter, query_one=query_parameter) + second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(header_two="header2", query_two=42) await client.parameter_grouping.post_multi_param_groups(first_group, second_group) @pytest.mark.asyncio async def test_post_some_multi_param_groups(self, client, header_parameter): - from azureparametergrouping.models import FirstParameterGroup, ParameterGroupingPostMultiParamGroupsSecondParamGroup - #Multiple grouped parameters -- some optional parameters omitted - first_group = FirstParameterGroup(header_one = header_parameter) - second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(query_two = 42) + from azureparametergrouping.models import ( + FirstParameterGroup, + ParameterGroupingPostMultiParamGroupsSecondParamGroup, + ) + + # Multiple grouped parameters -- some optional parameters omitted + first_group = FirstParameterGroup(header_one=header_parameter) + second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(query_two=42) await client.parameter_grouping.post_multi_param_groups(first_group, second_group) @pytest.mark.asyncio async def test_post_shared_parameter_group_object(self, client, header_parameter): from azureparametergrouping.models import FirstParameterGroup - first_group = FirstParameterGroup(header_one = header_parameter) + + first_group = FirstParameterGroup(header_one=header_parameter) await client.parameter_grouping.post_shared_parameter_group_object(first_group) @pytest.mark.asyncio async def test_post_reserved_words(self, client): from azureparametergrouping.models import ParameterGroupingPostReservedWordsParameters - group = ParameterGroupingPostReservedWordsParameters( - from_property="bob", - accept="yes" - ) + + group = ParameterGroupingPostReservedWordsParameters(from_property="bob", accept="yes") await client.parameter_grouping.post_reserved_words(group) @pytest.mark.asyncio @@ -196,4 +227,5 @@ async def test_azure_odata(self, azure_client): @pytest.mark.asyncio async def test_group_with_constant(self, client): from azureparametergrouping.models import Grouper + await client.parameter_grouping.group_with_constant(Grouper(grouped_constant="foo", grouped_parameter="bar")) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_policies.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_policies.py index b26f2666f68..57e54210ea4 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_policies.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_policies.py @@ -30,14 +30,18 @@ from azure.mgmt.core import AsyncARMPipelineClient import pytest + def get_policy_class_name(client) -> List[str]: - return [p._policy.__class__.__name__ if hasattr(p, "_policy") else p.__class__.__name__ for p in client._client._pipeline._impl_policies] + return [ + p._policy.__class__.__name__ if hasattr(p, "_policy") else p.__class__.__name__ + for p in client._client._pipeline._impl_policies + ] + @pytest.mark.parametrize( - "sdk_client,pipeline_client", [ - (AutoRestHeadTestService, AsyncARMPipelineClient), - (AutoRestDurationTestService, AsyncPipelineClient) -]) + "sdk_client,pipeline_client", + [(AutoRestHeadTestService, AsyncARMPipelineClient), (AutoRestDurationTestService, AsyncPipelineClient)], +) @pytest.mark.asyncio async def test_policies(sdk_client, pipeline_client): client = sdk_client(credential="") diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_security.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_security.py index 79c2ae272bc..8b5e87643f9 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_security.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_security.py @@ -28,11 +28,13 @@ from securitykeyswagger.aio import AutorestSecurityKey from azure.mgmt.core.policies import AsyncARMChallengeAuthenticationPolicy + @pytest.mark.asyncio async def test_security_aad(credential): client = AutorestSecurityAad(credential) assert isinstance(client._config.authentication_policy, AsyncARMChallengeAuthenticationPolicy) + @pytest.mark.asyncio async def test_security_key(credential): client = AutorestSecurityKey(credential) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_xms.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_xms.py index 29b73ec3642..799186e21d8 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_xms.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/asynctests/test_xms.py @@ -90,7 +90,9 @@ async def test_xms_request_client_id_in_client(self, client): async def test_xms_request_client_overwrite_via_parameter(self, client_no_request_id): # We DON'T support a Swagger parameter for request_id, the request_id policy will overwrite it. # We disable the request_id policy for this test - await client_no_request_id.xms_client_request_id.param_get(x_ms_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + await client_no_request_id.xms_client_request_id.param_get( + x_ms_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0" + ) @pytest.mark.asyncio async def test_xms_custom_named_request_id(self, client): @@ -101,4 +103,6 @@ async def test_xms_custom_named_request_id_parameter_group(self, client): param_group = models.HeaderCustomNamedRequestIdParamGroupingParameters( foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0" ) - await client.header.custom_named_request_id_param_grouping(header_custom_named_request_id_param_grouping_parameters=param_group) + await client.header.custom_named_request_id_param_grouping( + header_custom_named_request_id_param_grouping_parameters=param_group + ) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/conftest.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/conftest.py index 222d7fdebfe..6b2ca89b0c7 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/conftest.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/conftest.py @@ -38,21 +38,26 @@ cwd = dirname(realpath(__file__)) -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def start_server_process(): - cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format(cwd) - if os.name == 'nt': #On windows, subprocess creation works without being in the shell + cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format( + cwd + ) + if os.name == "nt": # On windows, subprocess creation works without being in the shell return subprocess.Popen(cmd) - return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) #On linux, have to set shell=True + return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # On linux, have to set shell=True + -#Ideally this would be in a common helper library shared between the tests +# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session") def testserver(): """Start the Autorest testserver.""" @@ -77,6 +82,7 @@ def on_response(self, request, response, **kwargs): if "Set-Cookie" in http_response.headers: self._current_cookie = http_response.headers["Set-Cookie"] + @pytest.fixture() def cookie_policy(): return CookiePolicy() @@ -87,11 +93,15 @@ def credential(): """I actually don't need anything, since the authentication policy will bypass it. """ + class FakeCredential: pass + return FakeCredential() + @pytest.fixture() def authentication_policy(): from azure.core.pipeline.policies import SansIOHTTPPolicy - return SansIOHTTPPolicy() \ No newline at end of file + + return SansIOHTTPPolicy() diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_custom_base_uri.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_custom_base_uri.py index 6e6934a5b2e..0cc35c7344d 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_custom_base_uri.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_custom_base_uri.py @@ -43,12 +43,14 @@ import pytest + @pytest.fixture def client(): with AutoRestParameterizedHostTestClient(host="host:3000") as client: client._config.retry_policy.retries = 0 yield client + class TestCustomBaseUri(object): def test_custom_base_uri_positive(self, client): @@ -71,6 +73,7 @@ def test_models(self): from custombaseurl.models import Error from custombaseurl.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -80,4 +83,5 @@ def test_operation_groups(self): from custombaseurl.operations import _paths_operations_py3 from custombaseurl.operations._paths_operations import PathsOperations as PathsOperationsPy2 + assert PathsOperations == PathsOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_url.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_url.py index fb545cd0c26..071e3a9ff6a 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_url.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_azure_url.py @@ -29,22 +29,26 @@ from subscriptionidapiversion import MicrosoftAzureTestUrl + class TestAzureUrl(object): def test_azure_url(self, credential, authentication_policy): sub_id = str(uuid4()) - with MicrosoftAzureTestUrl(credential, sub_id, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with MicrosoftAzureTestUrl( + credential, sub_id, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: group = client.group.get_sample_resource_group("testgoup101") - assert group.name == "testgroup101" - assert group.location == "West US" + assert group.name == "testgroup101" + assert group.location == "West US" def test_models(self): from subscriptionidapiversion.models import Error from subscriptionidapiversion.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -54,4 +58,5 @@ def test_operation_groups(self): from subscriptionidapiversion.operations import _group_operations_py3 from subscriptionidapiversion.operations._group_operations import GroupOperations as GroupOperationsPy2 + assert GroupOperations == GroupOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_config.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_config.py index cbf60b36f43..8764a62822f 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_config.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_config.py @@ -25,33 +25,43 @@ # -------------------------------------------------------------------------- from azure.mgmt.core.policies import ARMHttpLoggingPolicy, ARMChallengeAuthenticationPolicy + # Head is azure-arm from head import AutoRestHeadTestService + class TestConfig(object): def test_arm_http_logging_policy_default(self, credential): with AutoRestHeadTestService(credential, base_url="http://localhost:3000") as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) def test_arm_http_logging_policy_custom(self, credential): http_logging_policy = ARMHttpLoggingPolicy(base_url="test") http_logging_policy = ARMHttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) - with AutoRestHeadTestService(credential, base_url="http://localhost:3000", http_logging_policy=http_logging_policy) as client: + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) + with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", http_logging_policy=http_logging_policy + ) as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) def test_credential_scopes_default(self, credential): with AutoRestHeadTestService(credential) as client: - assert client._config.credential_scopes == ['https://management.azure.com/.default'] + assert client._config.credential_scopes == ["https://management.azure.com/.default"] def test_credential_scopes_override(self, credential): - with AutoRestHeadTestService(credential, credential_scopes=["http://i-should-be-the-only-credential"]) as client: + with AutoRestHeadTestService( + credential, credential_scopes=["http://i-should-be-the-only-credential"] + ) as client: assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] def test_credential_authentication_policy_default(self, credential): with AutoRestHeadTestService(credential, base_url="http://localhost:3000") as client: - assert isinstance(client._config.authentication_policy, ARMChallengeAuthenticationPolicy) \ No newline at end of file + assert isinstance(client._config.authentication_policy, ARMChallengeAuthenticationPolicy) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_custom_poller_pager.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_custom_poller_pager.py index ed7c9679ba5..31c1bf24f4e 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_custom_poller_pager.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_custom_poller_pager.py @@ -29,17 +29,23 @@ import pytest + @pytest.fixture def client(credential, authentication_policy): - with AutoRestPagingTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestPagingTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: yield client @pytest.fixture def custom_url_client(credential, authentication_policy): - with AutoRestParameterizedHostTestPagingClient(credential, host="host:3000", authentication_policy=authentication_policy) as client: + with AutoRestParameterizedHostTestPagingClient( + credential, host="host:3000", authentication_policy=authentication_policy + ) as client: yield client + class TestPaging(object): def test_custom_pager(self, client): pager = client.paging.get_single_pages() @@ -56,4 +62,5 @@ def test_operation_groups(self): from custompollerpager.operations import _paging_operations_py3 from custompollerpager.operations._paging_operations import PagingOperations as PagingOperationsPy2 + assert PagingOperations == PagingOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_duration.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_duration.py index 7dc744955cd..ef31ddf9b34 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_duration.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_duration.py @@ -41,11 +41,13 @@ import pytest + @pytest.fixture def client(): with AutoRestDurationTestService(base_url="http://localhost:3000") as client: yield client + class TestDuration(object): def test_get_null_and_invalid(self, client): @@ -62,6 +64,7 @@ def test_positive_duration(self, client): def test_models(self): from bodyduration.models import Error from bodyduration.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -71,4 +74,5 @@ def test_operation_groups(self): from bodyduration.operations import _duration_operations_py3 from bodyduration.operations._duration_operations import DurationOperations as DurationOperationsPy2 + assert DurationOperations == DurationOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_head.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_head.py index 707602a533a..092aba1a7c0 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_head.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_head.py @@ -42,11 +42,14 @@ import pytest + class TestHead(object): def test_head(self, credential, authentication_policy): - with AutoRestHeadTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: assert client.http_success.head200() assert client.http_success.head204() @@ -54,7 +57,9 @@ def test_head(self, credential, authentication_policy): def test_head_exception(self, credential, authentication_policy): - with AutoRestHeadExceptionTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadExceptionTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: client.head_exception.head200() client.head_exception.head204() @@ -68,6 +73,7 @@ def test_operation_groups(self): from head.operations import _http_success_operations_py3 from head.operations._http_success_operations import HttpSuccessOperations as HttpSuccessOperationsPy2 + assert HttpSuccessOperations == HttpSuccessOperationsPy2 from headexceptions.operations import HeadExceptionOperations @@ -75,5 +81,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from headexceptions.operations import _head_exception_operations_py3 - from headexceptions.operations._head_exception_operations import HeadExceptionOperations as HeadExceptionOperationsPy2 + from headexceptions.operations._head_exception_operations import ( + HeadExceptionOperations as HeadExceptionOperationsPy2, + ) + assert HeadExceptionOperations == HeadExceptionOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro.py index cb965db64e0..2cbb5dda965 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro.py @@ -54,6 +54,7 @@ POLLING_INTERVAL = 0 + class AutorestTestARMPolling(ARMPolling): def _polling_cookie(self, response): @@ -64,39 +65,38 @@ def _polling_cookie(self, response): otherwise an empty dictionary. """ parsed_url = urlparse(response.request.url) - host = parsed_url.hostname.strip('.') - if host == 'localhost': - return {'cookie': response.headers.get('set-cookie', '')} + host = parsed_url.hostname.strip(".") + if host == "localhost": + return {"cookie": response.headers.get("set-cookie", "")} return {} def request_status(self, status_link): request = self._client.get(status_link, headers=self._polling_cookie(self._pipeline_response.http_response)) # ARM requires to re-inject 'x-ms-client-request-id' while polling - if 'request_id' not in self._operation_config: - self._operation_config['request_id'] = self._get_request_id() + if "request_id" not in self._operation_config: + self._operation_config["request_id"] = self._get_request_id() return self._client._pipeline.run(request, stream=False, **self._operation_config) + @pytest.fixture() def client(cookie_policy, credential): """Create a AutoRestLongRunningOperationTestService client with test server credentials.""" - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - RetryPolicy(), - cookie_policy - ] - - with AutoRestLongRunningOperationTestService(credential, base_url="http://localhost:3000", policies=policies, polling_interval=POLLING_INTERVAL) as client: + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), RetryPolicy(), cookie_policy] + + with AutoRestLongRunningOperationTestService( + credential, base_url="http://localhost:3000", policies=policies, polling_interval=POLLING_INTERVAL + ) as client: yield client + @pytest.fixture() def product(): return Product(location="West US") + @pytest.fixture() def custom_headers(): - return {"x-ms-client-request-id": '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'} + return {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} class TestLro: @@ -108,7 +108,7 @@ def assert_raises_with_message(self, msg, func, *args, **kwargs): except HttpResponseError as err: assert err.response is not None - print("BODY: "+err.response.text()) + print("BODY: " + err.response.text()) try: msg, internal_msg = msg @@ -161,7 +161,9 @@ def test_happy_put201_creating_succeeded200(self, client, product): def test_happy_put201_creating_failed200(self, client, product): self.assert_raises_with_message( ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put201_creating_failed200, product) + client.lros.begin_put201_creating_failed200, + product, + ) process = self.lro_result(client.lros.begin_put201_creating_failed200, product, polling=False) assert "Created" == process.provisioning_state @@ -176,7 +178,9 @@ def test_happy_put200_updating_succeeded204(self, client, product): def test_happy_put200_acceptedcanceled200(self, client, product): self.assert_raises_with_message( ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put200_acceptedcanceled200, product) + client.lros.begin_put200_acceptedcanceled200, + product, + ) process = self.lro_result(client.lros.begin_put200_acceptedcanceled200, product, polling=False) assert "Accepted" == process.provisioning_state @@ -229,12 +233,14 @@ def test_happy_put_retry_succeeded(self, client, product): def test_happy_put_retry_failed_canceled(self, client, product): self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put_async_retry_failed, product) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_put_async_retry_failed, product + ) self.assert_raises_with_message( ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put_async_no_retrycanceled, product) + client.lros.begin_put_async_no_retrycanceled, + product, + ) def test_post202_retry200(self, client, product): process = self.lro_result(client.lros.begin_post202_retry200, product) @@ -251,12 +257,12 @@ def test_happy_delete_no_header_in_retry(self, client): def test_happy_delete_async_retry_failed_canceled(self, client): self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_delete_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_delete_async_retrycanceled + ) self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_delete_async_retry_failed) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_delete_async_retry_failed + ) def test_happy_delete_async_succeeded(self, client): assert self.lro_result(client.lros.begin_delete_async_no_retry_succeeded) is None @@ -267,24 +273,23 @@ def test_happy_delete_provisioning(self, client): assert "Succeeded" == process.provisioning_state result = self.lro_result(client.lros.begin_delete_provisioning202_deletingcanceled200) - assert result.provisioning_state == 'Canceled' + assert result.provisioning_state == "Canceled" result = self.lro_result(client.lros.begin_delete_provisioning202_deleting_failed200) - assert result.provisioning_state == 'Failed' + assert result.provisioning_state == "Failed" def test_happy_post(self, client, product): assert self.lro_result(client.lros.begin_post202_no_retry204, product) is None sku = self.lro_result(client.lros.begin_post200_with_payload) - assert sku.id == '1' + assert sku.id == "1" def test_happy_post_async_retry_failed_canceled(self, client, product): - self.assert_raises_with_message("Internal Server Error", - client.lros.begin_post_async_retry_failed) + self.assert_raises_with_message("Internal Server Error", client.lros.begin_post_async_retry_failed) self.assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_post_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_post_async_retrycanceled + ) def test_happy_post_async_succeeded(self, client, product): prod = self.lro_result(client.lros.begin_post_async_retry_succeeded) @@ -295,14 +300,14 @@ def test_happy_post_async_succeeded(self, client, product): def test_retrys_put(self, client, product): process = self.lro_result(client.lro_retrys.begin_put201_creating_succeeded200, product) - assert 'Succeeded' == process.provisioning_state + assert "Succeeded" == process.provisioning_state process = self.lro_result(client.lro_retrys.begin_put_async_relative_retry_succeeded, product) - assert 'Succeeded' == process.provisioning_state + assert "Succeeded" == process.provisioning_state def test_retrys_delete(self, client, product): process = self.lro_result(client.lro_retrys.begin_delete_provisioning202_accepted200_succeeded) - assert 'Succeeded' == process.provisioning_state + assert "Succeeded" == process.provisioning_state assert self.lro_result(client.lro_retrys.begin_delete202_retry200) is None assert self.lro_result(client.lro_retrys.begin_delete_async_relative_retry_succeeded) is None @@ -312,15 +317,21 @@ def test_retrys_post(self, client, product): assert self.lro_result(client.lro_retrys.begin_post_async_relative_retry_succeeded, product) is None def test_custom_headers_put_async_retry_succeeded(self, client, product, custom_headers): - process = self.lro_result(client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers) + process = self.lro_result( + client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers + ) assert process is not None def test_custom_headers_post_async_retry_succeeded(self, client, product, custom_headers): - process = self.lro_result(client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers) + process = self.lro_result( + client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers + ) assert process is None def test_custom_headers_put201_creating_succeeded200(self, client, product, custom_headers): - process = self.lro_result(client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers) + process = self.lro_result( + client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers + ) assert process is not None def test_custom_headers_post202_retry200(self, client, product, custom_headers): @@ -328,25 +339,35 @@ def test_custom_headers_post202_retry200(self, client, product, custom_headers): assert process is None def test_sads_put_non_retry(self, client, product): - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_put_non_retry400, product) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_put_non_retry400, product) - self.assert_raises_with_message("Error from the server", - client.lrosads.begin_put_non_retry201_creating400, product) + self.assert_raises_with_message( + "Error from the server", client.lrosads.begin_put_non_retry201_creating400, product + ) def test_sads_put_async_relative(self, client, product): - self.assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.lrosads.begin_put_async_relative_retry400, product) + self.assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", + client.lrosads.begin_put_async_relative_retry400, + product, + ) - self.assert_raises_with_message("no status found in body", - client.lrosads.begin_put_async_relative_retry_no_status, product) + self.assert_raises_with_message( + "no status found in body", client.lrosads.begin_put_async_relative_retry_no_status, product + ) - self.assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_async_relative_retry_no_status_payload, product) + self.assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_async_relative_retry_no_status_payload, + product, + ) def test_sads_put_error201_no_provisioning_state_payload(self, client, product): - self.assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_error201_no_provisioning_state_payload, product) + self.assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_error201_no_provisioning_state_payload, + product, + ) def test_sads_put200_invalid_json_with_exception(self, client, product): with pytest.raises(DecodeError): @@ -365,18 +386,16 @@ def test_sads_put_non_retry201_creating400_invalid_json_with_exception(self, cli def tests_lro_sads_delete_non_retry(self, client, product): - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_non_retry400) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_delete_non_retry400) - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_delete202_non_retry400) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_delete202_non_retry400) def test_sads_delete_async_relative(self, client, product): - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_async_relative_retry400) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_delete_async_relative_retry400) - self.assert_raises_with_message("no status found in body", - client.lrosads.begin_delete_async_relative_retry_no_status) + self.assert_raises_with_message( + "no status found in body", client.lrosads.begin_delete_async_relative_retry_no_status + ) def test_sads_delete204_succeeded(self, client): self.lro_result(client.lrosads.begin_delete204_succeeded) @@ -393,18 +412,17 @@ def test_sads_delete202_retry_invalid_header_with_exception(self, client): self.lro_result(client.lrosads.begin_delete202_retry_invalid_header) def test_sads_post_non_retry(self, client, product): - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_post_non_retry400, product) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_post_non_retry400, product) - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_post202_non_retry400, product) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_post202_non_retry400, product) def test_sads_post_async_relative(self, client, product): - self.assert_raises_with_message("Bad Request", - client.lrosads.begin_post_async_relative_retry400, product) + self.assert_raises_with_message("Bad Request", client.lrosads.begin_post_async_relative_retry400, product) - self.assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_post_async_relative_retry_no_payload) + self.assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_post_async_relative_retry_no_payload, + ) def test_sads_post202_no_location(self, client): # Testserver wants us to fail (coverage name is LROErrorPostNoLocation) @@ -422,7 +440,7 @@ def test_sads_post_async_relative_with_exception(self, client): def test_post202_retry_invalid_header_with_exception(self, client): with pytest.raises(Exception): - self.lro_result(client.lrosads.begin_post202_retry_invalid_header) + self.lro_result(client.lrosads.begin_post202_retry_invalid_header) def test_polling_interval_operation(self, client): default_polling_interval_start_time = time.time() @@ -444,14 +462,10 @@ def test_polling_interval_config(self, cookie_policy, credential, client): assert abs(default_polling_interval_duration - 0) < 3 # Now we create a new client with a polling_interval of 1 - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - RetryPolicy(), - cookie_policy - ] - client_one_second = AutoRestLongRunningOperationTestService(credential, base_url="http://localhost:3000", policies=policies, polling_interval=1) + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), RetryPolicy(), cookie_policy] + client_one_second = AutoRestLongRunningOperationTestService( + credential, base_url="http://localhost:3000", policies=policies, polling_interval=1 + ) one_second_polling_interval_start_time = time.time() product2 = client_one_second.lros.begin_post_double_headers_final_azure_header_get_default().result() one_second_polling_interval_duration = time.time() - one_second_polling_interval_start_time @@ -485,6 +499,7 @@ def test_models(self): from lro.models import OperationResult from lro.models._models_py3 import OperationResult as OperationResultPy3 + assert OperationResult == OperationResultPy3 def test_operation_groups(self): @@ -494,4 +509,5 @@ def test_operation_groups(self): from lro.operations import _lro_retrys_operations_py3 from lro.operations._lro_retrys_operations import LRORetrysOperations as LRORetrysOperationsPy2 + assert LRORetrysOperations == LRORetrysOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro_parameterized_endpoints.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro_parameterized_endpoints.py index 444f4d0b4bd..9c2f89f051f 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro_parameterized_endpoints.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_lro_parameterized_endpoints.py @@ -27,6 +27,7 @@ import pytest from lrowithparameterizedendpoints import LROWithParamaterizedEndpoints + @pytest.fixture def client(credential): with LROWithParamaterizedEndpoints(credential=credential, host="host:3000") as client: @@ -34,12 +35,14 @@ def client(credential): def test_poll_with_parameterized_endpoints(client): - poller = client.begin_poll_with_parameterized_endpoints(account_name='local', polling_interval=0) - assert poller.result() == 'success' + poller = client.begin_poll_with_parameterized_endpoints(account_name="local", polling_interval=0) + assert poller.result() == "success" + def test_poll_with_constant_parameterized_endpoints(client): - poller = client.begin_poll_with_constant_parameterized_endpoints(account_name='local', polling_interval=0) - assert poller.result() == 'success' + poller = client.begin_poll_with_constant_parameterized_endpoints(account_name="local", polling_interval=0) + assert poller.result() == "success" + def test_operation_groups(): from lrowithparameterizedendpoints.operations import LROWithParamaterizedEndpointsOperationsMixin @@ -47,5 +50,8 @@ def test_operation_groups(): with pytest.raises(ImportError): from lrowithparameterizedendpoints.operations import _lro_with_paramaterized_endpoints_operations_py3 - from lrowithparameterizedendpoints.operations._lro_with_paramaterized_endpoints_operations import LROWithParamaterizedEndpointsOperationsMixin as LROWithParamaterizedEndpointsOperationsMixinPy2 + from lrowithparameterizedendpoints.operations._lro_with_paramaterized_endpoints_operations import ( + LROWithParamaterizedEndpointsOperationsMixin as LROWithParamaterizedEndpointsOperationsMixinPy2, + ) + assert LROWithParamaterizedEndpointsOperationsMixin == LROWithParamaterizedEndpointsOperationsMixinPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_mixed_api_version.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_mixed_api_version.py index 3e7155f748a..96b3d845dc0 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_mixed_api_version.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_mixed_api_version.py @@ -26,16 +26,20 @@ from mixedapiversion import MixedApiVersionClient import pytest + @pytest.fixture def valid_subscription(): - return '1234-5678-9012-3456' + return "1234-5678-9012-3456" + @pytest.fixture def client(valid_subscription, credential, authentication_policy): - with MixedApiVersionClient(credential, valid_subscription, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with MixedApiVersionClient( + credential, valid_subscription, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: yield client + class TestMixedApiVersion(object): def test_mixed_api_version(self, client): client.api_version_default.get_method_global_valid() - diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_multi_client.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_multi_client.py index 121ddd766ba..629395611de 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_multi_client.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_multi_client.py @@ -26,6 +26,7 @@ from azure.packagemode.batch.head import HeadClient from azure.packagemode.batch.paging import PagingClient + class TestMultiClient(object): def test_head(self, credential, authentication_policy): diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_customize.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_customize.py index c65750163d2..d234b418277 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_customize.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_customize.py @@ -33,11 +33,14 @@ import pytest + class TestHead(object): def test_head(self, credential, authentication_policy): - with AutoRestHeadTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: assert client.http_success.head200() assert client.http_success.head204() @@ -45,7 +48,9 @@ def test_head(self, credential, authentication_policy): def test_head_exception(self, credential, authentication_policy): - with AutoRestHeadExceptionTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadExceptionTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: client.head_exception.head200() client.head_exception.head204() diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_data.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_data.py index b420c6a6003..769a5ce3528 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_data.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_data.py @@ -33,11 +33,14 @@ import pytest + class TestHead(object): def test_head(self, credential, authentication_policy): - with AutoRestHeadTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: assert client.http_success.head200() assert client.http_success.head204() @@ -45,7 +48,9 @@ def test_head(self, credential, authentication_policy): def test_head_exception(self, credential, authentication_policy): - with AutoRestHeadExceptionTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadExceptionTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: client.head_exception.head200() client.head_exception.head204() diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_mgmt.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_mgmt.py index f19db7c4955..e4e7e9df080 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_mgmt.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_package_mode_mgmt.py @@ -33,11 +33,14 @@ import pytest + class TestHead(object): def test_head(self, credential, authentication_policy): - with AutoRestHeadTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: assert client.http_success.head200() assert client.http_success.head204() @@ -45,7 +48,9 @@ def test_head(self, credential, authentication_policy): def test_head_exception(self, credential, authentication_policy): - with AutoRestHeadExceptionTestService(credential, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestHeadExceptionTestService( + credential, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: client.head_exception.head200() client.head_exception.head204() diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_paging.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_paging.py index b46e32c5a8c..75c0cfc071a 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_paging.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_paging.py @@ -43,6 +43,7 @@ import pytest + @pytest.fixture def client(): with AutoRestPagingTestService(base_url="http://localhost:3000") as client: @@ -54,6 +55,7 @@ def custom_url_client(): with AutoRestParameterizedHostTestPagingClient(host="host:3000") as client: yield client + class TestPaging(object): def test_get_no_item_name_pages(self, client): pages = client.paging.get_no_item_name_pages() @@ -81,6 +83,7 @@ def cb(list_of_obj): for obj in list_of_obj: obj.marked = True return list_of_obj + pages = client.paging.get_single_pages(cls=cb) assert all(obj.marked for obj in pages) @@ -104,7 +107,7 @@ def test_get_multiple_pages(self, client): assert len(items) == 10 def test_query_params(self, client): - pages = client.paging.get_with_query_params(required_query_parameter='100') + pages = client.paging.get_with_query_params(required_query_parameter="100") items = [i for i in pages] assert len(items) == 2 @@ -125,13 +128,13 @@ def test_get_multiple_pages_retry_second(self, client): def test_get_multiple_pages_with_offset(self, client): from paging.models import PagingGetMultiplePagesWithOffsetOptions + options = PagingGetMultiplePagesWithOffsetOptions(offset=100) pages = client.paging.get_multiple_pages_with_offset(paging_get_multiple_pages_with_offset_options=options) items = [i for i in pages] assert len(items) == 10 assert items[-1].properties.id == 110 - def test_get_single_pages_failure(self, client): pages = client.paging.get_single_pages_failure() with pytest.raises(HttpResponseError): @@ -172,9 +175,9 @@ def test_custom_url_get_pages_partial_url_operation(self, custom_url_client): assert paged[1].properties.id == 2 def test_get_multiple_pages_lro(self, client): - """LRO + Paging at the same time. - """ + """LRO + Paging at the same time.""" from azure.mgmt.core.polling.arm_polling import ARMPolling + poller = client.paging.begin_get_multiple_pages_lro(polling=ARMPolling(timeout=0)) pager = poller.result() @@ -215,6 +218,7 @@ def test_replace_api_version(self, client): def test_models(self): from paging.models import OperationResult from paging.models._models_py3 import OperationResult as OperationResultPy3 + assert OperationResult == OperationResultPy3 def test_operation_groups(self): @@ -224,6 +228,7 @@ def test_operation_groups(self): from paging.operations import _paging_operations_py3 from paging.operations._paging_operations import PagingOperations as PagingOperationsPy2 + assert PagingOperations == PagingOperationsPy2 from custombaseurlpaging.operations import PagingOperations @@ -232,4 +237,5 @@ def test_operation_groups(self): from custombaseurlpaging.operations import _paging_operations_py3 from custombaseurlpaging.operations._paging_operations import PagingOperations as PagingOperationsPy2 + assert PagingOperations == PagingOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_parameter.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_parameter.py index a207fdc952f..e39fa1a5cfb 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_parameter.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_parameter.py @@ -32,63 +32,83 @@ import pytest + @pytest.fixture def client(): with AutoRestParameterGroupingTestService(base_url="http://localhost:3000") as client: yield client + @pytest.fixture def valid_subscription(): - return '1234-5678-9012-3456' + return "1234-5678-9012-3456" + @pytest.fixture def azure_client(valid_subscription, credential, authentication_policy): - with AutoRestAzureSpecialParametersTestClient(credential, valid_subscription, base_url="http://localhost:3000", authentication_policy=authentication_policy) as client: + with AutoRestAzureSpecialParametersTestClient( + credential, valid_subscription, base_url="http://localhost:3000", authentication_policy=authentication_policy + ) as client: yield client + @pytest.fixture def body_parameter(): return 1234 + @pytest.fixture def header_parameter(): - return 'header' + return "header" + @pytest.fixture def query_parameter(): return 21 + @pytest.fixture def path_parameter(): - return 'path' + return "path" @pytest.fixture def unencoded_path(): - return 'path1/path2/path3' + return "path1/path2/path3" + @pytest.fixture def unencoded_query(): - return 'value1&q2=value2&q3=value3' + return "value1&q2=value2&q3=value3" + class TestParameter(object): - def test_post_all_required_parameters(self, client, body_parameter, header_parameter, query_parameter, path_parameter): + def test_post_all_required_parameters( + self, client, body_parameter, header_parameter, query_parameter, path_parameter + ): from azureparametergrouping.models import ParameterGroupingPostRequiredParameters + # Valid required parameters - required_parameters = ParameterGroupingPostRequiredParameters(body=body_parameter, path=path_parameter, custom_header=header_parameter, query=query_parameter) + required_parameters = ParameterGroupingPostRequiredParameters( + body=body_parameter, path=path_parameter, custom_header=header_parameter, query=query_parameter + ) client.parameter_grouping.post_required(required_parameters) def test_post_required_parameters_null_optional_parameters(self, client, body_parameter, path_parameter): from azureparametergrouping.models import ParameterGroupingPostRequiredParameters - #Required parameters but null optional parameters - required_parameters = ParameterGroupingPostRequiredParameters(body=body_parameter, path=path_parameter, query=None) + + # Required parameters but null optional parameters + required_parameters = ParameterGroupingPostRequiredParameters( + body=body_parameter, path=path_parameter, query=None + ) client.parameter_grouping.post_required(required_parameters) def test_post_required_parameters_with_null_required_property(self, client, path_parameter): from azureparametergrouping.models import ParameterGroupingPostRequiredParameters - #Required parameters object is not null, but a required property of the object is - required_parameters = ParameterGroupingPostRequiredParameters(body = None, path = path_parameter) + + # Required parameters object is not null, but a required property of the object is + required_parameters = ParameterGroupingPostRequiredParameters(body=None, path=path_parameter) with pytest.raises(ValidationError): client.parameter_grouping.post_required(required_parameters) @@ -96,42 +116,55 @@ def test_post_required_parameters_with_null_required_property(self, client, path client.parameter_grouping.post_required(None) def test_post_all_optional(self, client, header_parameter, query_parameter): - from azureparametergrouping.models import ParameterGroupingPostRequiredParameters, ParameterGroupingPostOptionalParameters - #Valid optional parameters - optional_parameters = ParameterGroupingPostOptionalParameters(custom_header = header_parameter, query = query_parameter) + from azureparametergrouping.models import ( + ParameterGroupingPostRequiredParameters, + ParameterGroupingPostOptionalParameters, + ) + + # Valid optional parameters + optional_parameters = ParameterGroupingPostOptionalParameters( + custom_header=header_parameter, query=query_parameter + ) client.parameter_grouping.post_optional(optional_parameters) def test_post_none_optional(self, client): - #null optional paramters + # null optional paramters client.parameter_grouping.post_optional(None) def test_post_all_multi_param_groups(self, client, header_parameter, query_parameter): - from azureparametergrouping.models import FirstParameterGroup, ParameterGroupingPostMultiParamGroupsSecondParamGroup - #Multiple grouped parameters - first_group = FirstParameterGroup(header_one = header_parameter, query_one = query_parameter) - second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(header_two = "header2", query_two = 42) + from azureparametergrouping.models import ( + FirstParameterGroup, + ParameterGroupingPostMultiParamGroupsSecondParamGroup, + ) + + # Multiple grouped parameters + first_group = FirstParameterGroup(header_one=header_parameter, query_one=query_parameter) + second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(header_two="header2", query_two=42) client.parameter_grouping.post_multi_param_groups(first_group, second_group) def test_post_some_multi_param_groups(self, client, header_parameter): - from azureparametergrouping.models import FirstParameterGroup, ParameterGroupingPostMultiParamGroupsSecondParamGroup - #Multiple grouped parameters -- some optional parameters omitted - first_group = FirstParameterGroup(header_one = header_parameter) - second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(query_two = 42) + from azureparametergrouping.models import ( + FirstParameterGroup, + ParameterGroupingPostMultiParamGroupsSecondParamGroup, + ) + + # Multiple grouped parameters -- some optional parameters omitted + first_group = FirstParameterGroup(header_one=header_parameter) + second_group = ParameterGroupingPostMultiParamGroupsSecondParamGroup(query_two=42) client.parameter_grouping.post_multi_param_groups(first_group, second_group) def test_post_shared_parameter_group_object(self, client, header_parameter): from azureparametergrouping.models import FirstParameterGroup - first_group = FirstParameterGroup(header_one = header_parameter) + + first_group = FirstParameterGroup(header_one=header_parameter) client.parameter_grouping.post_shared_parameter_group_object(first_group) def test_post_reserved_words(self, client): from azureparametergrouping.models import ParameterGroupingPostReservedWordsParameters - group = ParameterGroupingPostReservedWordsParameters( - from_property="bob", - accept="yes" - ) + + group = ParameterGroupingPostReservedWordsParameters(from_property="bob", accept="yes") client.parameter_grouping.post_reserved_words(group) def test_subscription_in_credentials(self, azure_client): @@ -175,13 +208,14 @@ def test_azure_odata(self, azure_client): def test_group_with_constant(self, client): from azureparametergrouping.models import Grouper - client.parameter_grouping.group_with_constant(Grouper(grouped_constant="foo", grouped_parameter="bar")) + client.parameter_grouping.group_with_constant(Grouper(grouped_constant="foo", grouped_parameter="bar")) def test_models(self): from azureparametergrouping.models import Error from azureparametergrouping.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -190,7 +224,10 @@ def test_operation_groups(self): with pytest.raises(ImportError): from azurespecialproperties.operations import _api_version_default_operations_py3 - from azurespecialproperties.operations._api_version_default_operations import ApiVersionDefaultOperations as ApiVersionDefaultOperationsPy2 + from azurespecialproperties.operations._api_version_default_operations import ( + ApiVersionDefaultOperations as ApiVersionDefaultOperationsPy2, + ) + assert ApiVersionDefaultOperations == ApiVersionDefaultOperationsPy2 from azureparametergrouping.operations import ParameterGroupingOperations @@ -198,5 +235,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from azureparametergrouping.operations import _parameter_grouping_operations_py3 - from azureparametergrouping.operations._parameter_grouping_operations import ParameterGroupingOperations as ParameterGroupingOperationsPy2 + from azureparametergrouping.operations._parameter_grouping_operations import ( + ParameterGroupingOperations as ParameterGroupingOperationsPy2, + ) + assert ParameterGroupingOperations == ParameterGroupingOperationsPy2 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_policies.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_policies.py index 4b5becd6d72..c99af4dc5a9 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_policies.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_policies.py @@ -30,14 +30,18 @@ from azure.mgmt.core import ARMPipelineClient import pytest + def get_policy_class_name(client) -> List[str]: - return [p._policy.__class__.__name__ if hasattr(p, "_policy") else p.__class__.__name__ for p in client._client._pipeline._impl_policies] + return [ + p._policy.__class__.__name__ if hasattr(p, "_policy") else p.__class__.__name__ + for p in client._client._pipeline._impl_policies + ] + @pytest.mark.parametrize( - "sdk_client,pipeline_client", [ - (AutoRestHeadTestService, ARMPipelineClient), - (AutoRestDurationTestService, PipelineClient) -]) + "sdk_client,pipeline_client", + [(AutoRestHeadTestService, ARMPipelineClient), (AutoRestDurationTestService, PipelineClient)], +) def test_policies(sdk_client, pipeline_client): client = sdk_client(credential="") policies_built_in_client = get_policy_class_name(client) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_security.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_security.py index 0c1ed4b4dfd..81ca0cf3130 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_security.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_security.py @@ -27,10 +27,12 @@ from securitykeyswagger import AutorestSecurityKey from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy + def test_security_aad(credential): client = AutorestSecurityAad(credential) assert isinstance(client._config.authentication_policy, ARMChallengeAuthenticationPolicy) + def test_security_key(credential): client = AutorestSecurityKey(credential) assert isinstance(client._config.authentication_policy, ARMChallengeAuthenticationPolicy) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_tracing.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_tracing.py index 397e9176db7..3ebdfa88987 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_tracing.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_tracing.py @@ -49,6 +49,7 @@ def test_lro(): assert not has_tracing_decorator(client.lros._put201_creating_succeeded200_initial) assert has_tracing_decorator(client.lros.begin_put201_creating_succeeded200) + def test_azure_url(): client = MicrosoftAzureTestUrl("cred", "sub_id", base_url="dummy url") assert has_tracing_decorator(client.group.get_sample_resource_group) diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_xms.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_xms.py index e56e7222d3b..185b29dc7e6 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_xms.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_xms.py @@ -81,7 +81,9 @@ def test_xms_request_client_id_in_client(self, client): def test_xms_request_client_overwrite_via_parameter(self, client_no_request_id): # We DON'T support a Swagger parameter for request_id, the request_id policy will overwrite it. # We disable the request_id policy for this test - client_no_request_id.xms_client_request_id.param_get(x_ms_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + client_no_request_id.xms_client_request_id.param_get( + x_ms_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0" + ) def test_xms_custom_named_request_id(self, client): client.header.custom_named_request_id(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") @@ -90,10 +92,13 @@ def test_xms_custom_named_request_id_parameter_group(self, client): param_group = models.HeaderCustomNamedRequestIdParamGroupingParameters( foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0" ) - client.header.custom_named_request_id_param_grouping(header_custom_named_request_id_param_grouping_parameters=param_group) + client.header.custom_named_request_id_param_grouping( + header_custom_named_request_id_param_grouping_parameters=param_group + ) def test_models(self): from azurespecialproperties.models import Error from azurespecialproperties.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 diff --git a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_zzz.py b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_zzz.py index fe7465b4e32..bf88cfe55e8 100644 --- a/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_zzz.py +++ b/packages/autorest.python/test/azure/legacy/AcceptanceTests/test_zzz.py @@ -50,7 +50,6 @@ def test_ensure_coverage(self): print("Coverage:") self._print_report(report, not_supported, missing_features_or_bugs) - def _print_report(self, report, not_supported=None, missing_features_or_bugs=None): if not_supported: report.update(not_supported) @@ -67,6 +66,6 @@ def _print_report(self, report, not_supported=None, missing_features_or_bugs=Non print("FAILED TO EXECUTE {0}".format(s)) total_tests = len(report) - warnings.warn ("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) + warnings.warn("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) - #assert 0 == len(failed) + # assert 0 == len(failed) diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/__init__.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/__init__.py index 9ecdd4ff2c4..c36aaed1490 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/__init__.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/__init__.py @@ -22,4 +22,4 @@ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # -# -------------------------------------------------------------------------- \ No newline at end of file +# -------------------------------------------------------------------------- diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_custom_base_uri.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_custom_base_uri.py index 45918459223..e2803b6e205 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_custom_base_uri.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_custom_base_uri.py @@ -25,7 +25,7 @@ # -------------------------------------------------------------------------- from async_generator import yield_, async_generator -import pytest +import pytest from azure.core.exceptions import ServiceRequestError from custombaseurlversiontolerant.aio import AutoRestParameterizedHostTestClient @@ -38,20 +38,24 @@ async def client(): client._config.retry_policy.retries = 0 await yield_(client) + @pytest.mark.asyncio async def test_custom_base_uri_positive(client): await client.paths.get_empty("local") + @pytest.mark.asyncio async def test_custom_base_uri_get_empty(client): with pytest.raises(ServiceRequestError): await client.paths.get_empty("bad") + @pytest.mark.asyncio async def test_custom_base_uri_get_none(client): with pytest.raises(ValueError): await client.paths.get_empty(None) + @pytest.mark.asyncio async def test_custom_base_uri_bad_host(client): client._config.host = "badhost:3000" diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_url.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_url.py index fc3ab29090d..41601eb3440 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_url.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_azure_url.py @@ -38,5 +38,5 @@ async def test_azure_url(credential, authentication_policy): async with MicrosoftAzureTestUrl(credential, sub_id, authentication_policy=authentication_policy) as client: group = await client.group.get_sample_resource_group("testgoup101") - assert group['name'] == "testgroup101" - assert group['location'] == "West US" + assert group["name"] == "testgroup101" + assert group["location"] == "West US" diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_config.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_config.py index 409d050f3e2..fb83112c599 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_config.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_config.py @@ -25,32 +25,40 @@ # -------------------------------------------------------------------------- import pytest from azure.mgmt.core.policies import ARMHttpLoggingPolicy + # Head is azure-arm from headversiontolerant.aio import AutoRestHeadTestService + @pytest.mark.asyncio async def test_arm_http_logging_policy_default(credential): async with AutoRestHeadTestService(credential) as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + @pytest.mark.asyncio async def test_arm_http_logging_policy_custom(credential): http_logging_policy = ARMHttpLoggingPolicy(base_url="test") http_logging_policy = ARMHttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) async with AutoRestHeadTestService(credential, http_logging_policy=http_logging_policy) as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) + @pytest.mark.asyncio async def test_credential_scopes_default(credential): async with AutoRestHeadTestService(credential) as client: - assert client._config.credential_scopes == ['https://management.azure.com/.default'] + assert client._config.credential_scopes == ["https://management.azure.com/.default"] + @pytest.mark.asyncio async def test_credential_scopes_override(credential): - async with AutoRestHeadTestService(credential, credential_scopes=["http://i-should-be-the-only-credential"]) as client: + async with AutoRestHeadTestService( + credential, credential_scopes=["http://i-should-be-the-only-credential"] + ) as client: assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_custom_poller_pager.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_custom_poller_pager.py index 396500c25cb..8604c2f4c9e 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_custom_poller_pager.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_custom_poller_pager.py @@ -29,17 +29,22 @@ import pytest + @pytest.fixture @async_generator async def client(credential, authentication_policy): - async with AutoRestPagingTestService(credential, host="host:3000", authentication_policy=authentication_policy) as client: + async with AutoRestPagingTestService( + credential, host="host:3000", authentication_policy=authentication_policy + ) as client: await yield_(client) + def test_custom_pager(client): pager = client.paging.get_single_pages() assert isinstance(pager, AsyncCustomPager) + @pytest.mark.asyncio async def test_custom_poller(client): poller = await client.paging.begin_get_multiple_pages_lro() - assert isinstance(poller, AsyncCustomPoller) \ No newline at end of file + assert isinstance(poller, AsyncCustomPoller) diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_duration.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_duration.py index c1618165e78..38847711cbd 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_duration.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_duration.py @@ -32,12 +32,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDurationTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_get_null_and_invalid(client): assert await client.duration.get_null() is None @@ -45,6 +47,7 @@ async def test_get_null_and_invalid(client): with pytest.raises(isodate.ISO8601Error): deserialize_duration(await client.duration.get_invalid()) + @pytest.mark.asyncio async def test_positive_duration(client): await client.duration.get_positive_duration() diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_head.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_head.py index 7a171a5df25..9d2719d467d 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_head.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_head.py @@ -29,6 +29,8 @@ from azure.core.exceptions import HttpResponseError import pytest + + @pytest.mark.asyncio async def test_head(credential, authentication_policy): @@ -38,6 +40,7 @@ async def test_head(credential, authentication_policy): assert await client.http_success.head204() assert not await client.http_success.head404() + @pytest.mark.asyncio async def test_head_exception(credential, authentication_policy): diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro.py index c27bf1ad9eb..56b7f045a05 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro.py @@ -44,6 +44,7 @@ POLLING_INTERVAL = 0 + class AutorestTestARMPolling(AsyncARMPolling): def _polling_cookie(self, response): @@ -54,31 +55,28 @@ def _polling_cookie(self, response): otherwise an empty dictionary. """ parsed_url = urlparse(response.request.url) - host = parsed_url.hostname.strip('.') - if host == 'localhost': - return {'cookie': response.headers.get('set-cookie', '')} + host = parsed_url.hostname.strip(".") + if host == "localhost": + return {"cookie": response.headers.get("set-cookie", "")} return {} async def request_status(self, status_link): request = HttpRequest("GET", status_link, headers=self._polling_cookie(self._pipeline_response.http_response)) # ARM requires to re-inject 'x-ms-client-request-id' while polling - if 'request_id' not in self._operation_config: - self._operation_config['request_id'] = self._get_request_id() - return (await self._client._pipeline.run(request, stream=False, **self._operation_config)) + if "request_id" not in self._operation_config: + self._operation_config["request_id"] = self._get_request_id() + return await self._client._pipeline.run(request, stream=False, **self._operation_config) + @pytest.fixture @async_generator async def client(cookie_policy, credential): """Create a AutoRestLongRunningOperationTestService client with test server credentials.""" - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] - async with AutoRestLongRunningOperationTestService(credential=credential, policies=policies, polling_interval=POLLING_INTERVAL) as client: + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), AsyncRetryPolicy(), cookie_policy] + async with AutoRestLongRunningOperationTestService( + credential=credential, policies=policies, polling_interval=POLLING_INTERVAL + ) as client: await yield_(client) @@ -86,9 +84,11 @@ async def client(cookie_policy, credential): def product(): return {"location": "West US"} + @pytest.fixture() def custom_headers(): - return {"x-ms-client-request-id": '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'} + return {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} + async def assert_raises_with_message(msg, func, *args, **kwargs): try: @@ -97,7 +97,7 @@ async def assert_raises_with_message(msg, func, *args, **kwargs): except HttpResponseError as err: assert err.response is not None - print("BODY: "+err.response.text()) + print("BODY: " + err.response.text()) try: msg, internal_msg = msg @@ -114,12 +114,14 @@ async def assert_raises_with_message(msg, func, *args, **kwargs): if internal_msg: assert internal_msg in str(err.inner_exception) + async def lro_result(func, *args, **kwargs): if "polling" not in kwargs: AutorestTestARMPolling.__name__ = "AsyncARMPolling" kwargs["polling"] = AutorestTestARMPolling(0) return await (await func(*args, **kwargs)).result() + @pytest.mark.asyncio async def test_post_double_headers_final(client): poller = await client.lros.begin_post_double_headers_final_location_get() @@ -129,6 +131,7 @@ async def test_post_double_headers_final(client): product = await poller.result() assert product["id"] == "100" + @pytest.mark.asyncio async def test_post_double_headers_default(client): # This test will work as long as the default is Location @@ -136,56 +139,63 @@ async def test_post_double_headers_default(client): product = await poller.result() assert product["id"] == "100" + @pytest.mark.asyncio async def test_happy_put201_creating_succeeded200(client, product): process = await lro_result(client.lros.begin_put201_creating_succeeded200, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] # Testing nopolling process = await lro_result(client.lros.begin_put201_creating_succeeded200, product, polling=False) - assert "Creating" == process['properties']['provisioningState'] + assert "Creating" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put201_creating_failed200(client, product): await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put201_creating_failed200, product) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_put201_creating_failed200, product + ) process = await lro_result(client.lros.begin_put201_creating_failed200, product, polling=False) - assert "Created" == process['properties']['provisioningState'] + assert "Created" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put200_updating_succeeded204(client, product): process = await lro_result(client.lros.begin_put200_updating_succeeded204, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = await lro_result(client.lros.begin_put200_updating_succeeded204, product, polling=False) - assert "Updating" == process['properties']['provisioningState'] + assert "Updating" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put200_acceptedcanceled200(client, product): await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put200_acceptedcanceled200, product) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_put200_acceptedcanceled200, product + ) process = await lro_result(client.lros.begin_put200_acceptedcanceled200, product, polling=False) - assert "Accepted" == process['properties']['provisioningState'] + assert "Accepted" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put_no_header_in_retry(client, product): process = await lro_result(client.lros.begin_put_no_header_in_retry, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = await lro_result(client.lros.begin_put_async_no_header_in_retry, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put_sub_resource(client): process = await lro_result(client.lros.begin_put_sub_resource, {}) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = await lro_result(client.lros.begin_put_async_sub_resource, {}) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put_non_resource(client): @@ -195,102 +205,115 @@ async def test_happy_put_non_resource(client): process = await lro_result(client.lros.begin_put_async_non_resource, {}) assert "100" == process["id"] + @pytest.mark.asyncio async def test_happy_put200_succeeded(client, product): process = await lro_result(client.lros.begin_put200_succeeded, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = await lro_result(client.lros.begin_put200_succeeded_no_state, product) assert "100" == process["id"] + @pytest.mark.asyncio async def test_put201_succeeded(client, product): process = await lro_result(client.lros.begin_put201_succeeded, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] assert "100" == process["id"] assert "foo" == process["name"] + @pytest.mark.asyncio async def test_happy_put202_retry200(client, product): process = await lro_result(client.lros.begin_put202_retry200, product) assert "100" == process["id"] + @pytest.mark.asyncio async def test_happy_put_retry_succeeded(client, product): process = await lro_result(client.lros.begin_put_async_retry_succeeded, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = await lro_result(client.lros.begin_put_async_no_retry_succeeded, product) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_happy_put_retry_failed_canceled(client, product): await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put_async_retry_failed, product) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_put_async_retry_failed, product + ) await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put_async_no_retrycanceled, product) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_put_async_no_retrycanceled, product + ) + @pytest.mark.asyncio async def test_post202_retry200(client, product): process = await lro_result(client.lros.begin_post202_retry200, product) assert process is None + @pytest.mark.asyncio async def test_happy_delete(client): assert await lro_result(client.lros.begin_delete204_succeeded) is None assert await lro_result(client.lros.begin_delete202_retry200) is None assert await lro_result(client.lros.begin_delete202_no_retry204) is None + @pytest.mark.asyncio async def test_happy_delete_no_header_in_retry(client): assert await lro_result(client.lros.begin_delete_no_header_in_retry) is None assert await lro_result(client.lros.begin_delete_async_no_header_in_retry) is None + @pytest.mark.asyncio async def test_happy_delete_async_retry_failed_canceled(client): await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_delete_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_delete_async_retrycanceled + ) await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_delete_async_retry_failed) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_delete_async_retry_failed + ) + @pytest.mark.asyncio async def test_happy_delete_async_succeeded(client): assert await lro_result(client.lros.begin_delete_async_no_retry_succeeded) is None assert await lro_result(client.lros.begin_delete_async_retry_succeeded) is None + @pytest.mark.asyncio async def test_happy_delete_provisioning(client): process = await lro_result(client.lros.begin_delete_provisioning202_accepted200_succeeded) - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] result = await lro_result(client.lros.begin_delete_provisioning202_deletingcanceled200) - assert result['properties']['provisioningState'] == 'Canceled' + assert result["properties"]["provisioningState"] == "Canceled" result = await lro_result(client.lros.begin_delete_provisioning202_deleting_failed200) - assert result['properties']['provisioningState'] == 'Failed' + assert result["properties"]["provisioningState"] == "Failed" + @pytest.mark.asyncio async def test_happy_post(client, product): assert await lro_result(client.lros.begin_post202_no_retry204, product) is None sku = await lro_result(client.lros.begin_post200_with_payload) - assert sku["id"] == '1' + assert sku["id"] == "1" + @pytest.mark.asyncio async def test_happy_post_async_retry_failed_canceled(client, product): - await assert_raises_with_message("Internal Server Error", - client.lros.begin_post_async_retry_failed) + await assert_raises_with_message("Internal Server Error", client.lros.begin_post_async_retry_failed) await assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_post_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_post_async_retrycanceled + ) + @pytest.mark.asyncio async def test_happy_post_async_succeeded(client, product): @@ -300,76 +323,102 @@ async def test_happy_post_async_succeeded(client, product): prod = await lro_result(client.lros.begin_post_async_no_retry_succeeded) assert prod["id"] == "100" + @pytest.mark.asyncio async def test_retrys_put(client, product): process = await lro_result(client.lro_retrys.begin_put201_creating_succeeded200, product) - assert 'Succeeded' == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = await lro_result(client.lro_retrys.begin_put_async_relative_retry_succeeded, product) - assert 'Succeeded' == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_retrys_delete(client, product): process = await lro_result(client.lro_retrys.begin_delete_provisioning202_accepted200_succeeded) - assert 'Succeeded' == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] assert await lro_result(client.lro_retrys.begin_delete202_retry200) is None assert await lro_result(client.lro_retrys.begin_delete_async_relative_retry_succeeded) is None + @pytest.mark.asyncio async def test_retrys_post(client, product): assert await lro_result(client.lro_retrys.begin_post202_retry200, product) is None assert await lro_result(client.lro_retrys.begin_post_async_relative_retry_succeeded, product) is None + @pytest.mark.asyncio async def test_custom_headers_put_async_retry_succeeded(client, product, custom_headers): - process = await lro_result(client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers) + process = await lro_result( + client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers + ) assert process is not None + @pytest.mark.asyncio async def test_custom_headers_post_async_retry_succeeded(client, product, custom_headers): - process = await lro_result(client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers) + process = await lro_result( + client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers + ) assert process is None + @pytest.mark.asyncio async def test_custom_headers_put201_creating_succeeded200(client, product, custom_headers): - process = await lro_result(client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers) + process = await lro_result( + client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers + ) assert process is not None + @pytest.mark.asyncio async def test_custom_headers_post202_retry200(client, product, custom_headers): process = await lro_result(client.lr_os_custom_header.begin_post202_retry200, product, headers=custom_headers) assert process is None + @pytest.mark.asyncio async def test_sads_put_non_retry(client, product): - await assert_raises_with_message("Bad Request", - client.lrosads.begin_put_non_retry400, product) + await assert_raises_with_message("Bad Request", client.lrosads.begin_put_non_retry400, product) + + await assert_raises_with_message( + "Error from the server", client.lrosads.begin_put_non_retry201_creating400, product + ) - await assert_raises_with_message("Error from the server", - client.lrosads.begin_put_non_retry201_creating400, product) @pytest.mark.asyncio async def test_sads_put_async_relative(client, product): - await assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.lrosads.begin_put_async_relative_retry400, product) + await assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", client.lrosads.begin_put_async_relative_retry400, product + ) + + await assert_raises_with_message( + "no status found in body", client.lrosads.begin_put_async_relative_retry_no_status, product + ) - await assert_raises_with_message("no status found in body", - client.lrosads.begin_put_async_relative_retry_no_status, product) + await assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_async_relative_retry_no_status_payload, + product, + ) - await assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_async_relative_retry_no_status_payload, product) @pytest.mark.asyncio async def test_sads_put_error201_no_provisioning_state_payload(client, product): - await assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_error201_no_provisioning_state_payload, product) + await assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_error201_no_provisioning_state_payload, + product, + ) + @pytest.mark.asyncio async def test_sads_put200_invalid_json_with_exception(client, product): with pytest.raises(DecodeError): await lro_result(client.lrosads.begin_put200_invalid_json, product) + @pytest.mark.asyncio async def test_sads_put_async_relative_with_exception(client, product): with pytest.raises(DecodeError): @@ -378,32 +427,35 @@ async def test_sads_put_async_relative_with_exception(client, product): with pytest.raises(Exception): await lro_result(client.lrosads.begin_put_async_relative_retry_invalid_header, product) + @pytest.mark.asyncio async def test_sads_put_non_retry201_creating400_invalid_json_with_exception(client, product): with pytest.raises(DecodeError): await lro_result(client.lrosads.begin_put_non_retry201_creating400_invalid_json, product) + @pytest.mark.asyncio async def tests_lro_sads_delete_non_retry(client, product): - await assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_non_retry400) + await assert_raises_with_message("Bad Request", client.lrosads.begin_delete_non_retry400) + + await assert_raises_with_message("Bad Request", client.lrosads.begin_delete202_non_retry400) - await assert_raises_with_message("Bad Request", - client.lrosads.begin_delete202_non_retry400) @pytest.mark.asyncio async def test_sads_delete_async_relative(client, product): - await assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_async_relative_retry400) + await assert_raises_with_message("Bad Request", client.lrosads.begin_delete_async_relative_retry400) + + await assert_raises_with_message( + "no status found in body", client.lrosads.begin_delete_async_relative_retry_no_status + ) - await assert_raises_with_message("no status found in body", - client.lrosads.begin_delete_async_relative_retry_no_status) @pytest.mark.asyncio async def test_sads_delete204_succeeded(client): await lro_result(client.lrosads.begin_delete204_succeeded) + @pytest.mark.asyncio async def test_sads_delete_async_relative_with_exception(client): with pytest.raises(Exception): @@ -412,26 +464,29 @@ async def test_sads_delete_async_relative_with_exception(client): with pytest.raises(DecodeError): await lro_result(client.lrosads.begin_delete_async_relative_retry_invalid_json_polling) + @pytest.mark.asyncio async def test_sads_delete202_retry_invalid_header_with_exception(client): with pytest.raises(Exception): await lro_result(client.lrosads.begin_delete202_retry_invalid_header) + @pytest.mark.asyncio async def test_sads_post_non_retry(client, product): - await assert_raises_with_message("Bad Request", - client.lrosads.begin_post_non_retry400, product) + await assert_raises_with_message("Bad Request", client.lrosads.begin_post_non_retry400, product) + + await assert_raises_with_message("Bad Request", client.lrosads.begin_post202_non_retry400, product) - await assert_raises_with_message("Bad Request", - client.lrosads.begin_post202_non_retry400, product) @pytest.mark.asyncio async def test_sads_post_async_relative(client, product): - await assert_raises_with_message("Bad Request", - client.lrosads.begin_post_async_relative_retry400, product) + await assert_raises_with_message("Bad Request", client.lrosads.begin_post_async_relative_retry400, product) + + await assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_post_async_relative_retry_no_payload, + ) - await assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_post_async_relative_retry_no_payload) @pytest.mark.asyncio async def test_sads_post202_no_location(client): @@ -441,6 +496,7 @@ async def test_sads_post202_no_location(client): process = await lro_result(client.lrosads.begin_post202_no_location) assert process is None + @pytest.mark.asyncio async def test_sads_post_async_relative_with_exception(client): with pytest.raises(Exception): @@ -449,10 +505,12 @@ async def test_sads_post_async_relative_with_exception(client): with pytest.raises(DecodeError): await lro_result(client.lrosads.begin_post_async_relative_retry_invalid_json_polling) + @pytest.mark.asyncio async def test_post202_retry_invalid_header_with_exception(client): with pytest.raises(Exception): - await lro_result(client.lrosads.begin_post202_retry_invalid_header) + await lro_result(client.lrosads.begin_post202_retry_invalid_header) + @pytest.mark.asyncio async def test_polling_interval_operation(client): @@ -470,6 +528,7 @@ async def test_polling_interval_operation(client): assert product1 == product2 + @pytest.mark.asyncio async def test_polling_interval_config(cookie_policy, credential, client): default_polling_interval_start_time = time.time() @@ -479,14 +538,10 @@ async def test_polling_interval_config(cookie_policy, credential, client): assert abs(default_polling_interval_duration - 0) < 3 # Now we create a new client with a polling_interval of 1 - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] - client_one_second = AutoRestLongRunningOperationTestService(credential=credential, policies=policies, polling_interval=1) + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), AsyncRetryPolicy(), cookie_policy] + client_one_second = AutoRestLongRunningOperationTestService( + credential=credential, policies=policies, polling_interval=1 + ) one_second_polling_interval_start_time = time.time() poller = await client_one_second.lros.begin_post_double_headers_final_azure_header_get_default() product2 = await poller.result() @@ -494,10 +549,12 @@ async def test_polling_interval_config(cookie_policy, credential, client): assert abs(one_second_polling_interval_duration - 1) < 3 assert product1 == product2 + @pytest.mark.asyncio async def test_passing_kwargs(client, product): process = await lro_result(client.lros.begin_put200_succeeded, product, content_type="application/json") - assert "Succeeded" == process['properties']['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + @pytest.mark.asyncio async def test_lro_list(client, product): @@ -505,14 +562,24 @@ async def test_lro_list(client, product): assert len(products) == 1 product = products[0] assert product["id"] == "100" - assert product["name"]== "foo" + assert product["name"] == "foo" + @pytest.mark.asyncio async def test_patch201_retry_with_async_header(client, product): product = await lro_result(client.lros.begin_patch201_retry_with_async_header, product) - assert product == {"properties": {"provisioningState": "Succeeded"}, "id": "/lro/patch/201/retry/onlyAsyncHeader", "name": "foo"} + assert product == { + "properties": {"provisioningState": "Succeeded"}, + "id": "/lro/patch/201/retry/onlyAsyncHeader", + "name": "foo", + } + @pytest.mark.asyncio async def test_patch202_retry_with_async_and_location_header(client, product): product = await lro_result(client.lros.begin_patch202_retry_with_async_and_location_header, product) - assert product == { "properties": { "provisioningState": "Succeeded"}, "id": "/lro/patch/202/retry/asyncAndLocationHeader", "name": "foo" } + assert product == { + "properties": {"provisioningState": "Succeeded"}, + "id": "/lro/patch/202/retry/asyncAndLocationHeader", + "name": "foo", + } diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_paging.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_paging.py index d5355f4480c..accbab79f5e 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_paging.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_paging.py @@ -27,11 +27,13 @@ from lropagingversiontolerant.aio import LroPagingClient from azure.core.exceptions import ResourceNotFoundError + @pytest.fixture() async def client(): async with LroPagingClient() as client: yield client + @pytest.mark.asyncio async def test_begin_update_qnas(client): with pytest.raises(ResourceNotFoundError): diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py index 2972f4c37a9..839b72dca29 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_lro_parameterized_endpoints.py @@ -27,18 +27,21 @@ from lrowithparameterizedendpointsversiontolerant.aio import LROWithParamaterizedEndpoints from async_generator import yield_, async_generator + @pytest.fixture @async_generator async def client(credential): async with LROWithParamaterizedEndpoints(credential=credential, host="host:3000") as client: await yield_(client) + @pytest.mark.asyncio async def test_poll_with_parameterized_endpoints(client): - poller = await client.begin_poll_with_parameterized_endpoints(account_name='local', polling_interval=0) - assert (await poller.result()) == 'success' + poller = await client.begin_poll_with_parameterized_endpoints(account_name="local", polling_interval=0) + assert (await poller.result()) == "success" + @pytest.mark.asyncio async def test_poll_with_constant_parameterized_endpoints(client): - poller = await client.begin_poll_with_constant_parameterized_endpoints(account_name='local', polling_interval=0) - assert (await poller.result()) == 'success' + poller = await client.begin_poll_with_constant_parameterized_endpoints(account_name="local", polling_interval=0) + assert (await poller.result()) == "success" diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_paging.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_paging.py index 6670c65fa3a..0bb34abf752 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_paging.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_paging.py @@ -34,25 +34,22 @@ import pytest + @pytest.fixture @async_generator async def client(cookie_policy): - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), AsyncRetryPolicy(), cookie_policy] async with AutoRestPagingTestService(policies=policies) as client: await yield_(client) + @pytest.fixture @async_generator async def custom_url_client(): async with AutoRestParameterizedHostTestPagingClient(host="host:3000") as client: await yield_(client) + @pytest.mark.asyncio async def test_get_no_item_name_pages(client): pages = client.paging.get_no_item_name_pages() @@ -63,6 +60,7 @@ async def test_get_no_item_name_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_get_null_next_link_name_pages(client): pages = client.paging.get_null_next_link_name_pages() @@ -73,6 +71,7 @@ async def test_get_null_next_link_name_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_get_empty_next_link_name_pages(client): pages = client.paging.get_empty_next_link_name_pages() @@ -81,15 +80,18 @@ async def test_get_empty_next_link_name_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_get_single_pages_with_cb(client): def cb(list_of_obj): for obj in list_of_obj: obj["marked"] = True return list_of_obj + async for obj in client.paging.get_single_pages(cls=cb): assert obj["marked"] + @pytest.mark.asyncio async def test_get_single_pages(client): pages = client.paging.get_single_pages() @@ -100,6 +102,7 @@ async def test_get_single_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_get_single_pages_with_body_params(client): pages = client.paging.get_single_pages_with_body_params({"name": "body"}) @@ -110,6 +113,7 @@ async def test_get_single_pages_with_body_params(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_get_multiple_pages(client): pages = client.paging.get_multiple_pages() @@ -118,14 +122,16 @@ async def test_get_multiple_pages(client): items.append(item) assert len(items) == 10 + @pytest.mark.asyncio async def test_query_params(client): - pages = client.paging.get_with_query_params(required_query_parameter='100') + pages = client.paging.get_with_query_params(required_query_parameter="100") items = [] async for item in pages: items.append(item) assert len(items) == 2 + @pytest.mark.asyncio async def test_get_odata_multiple_pages(client): pages = client.paging.get_odata_multiple_pages() @@ -134,6 +140,7 @@ async def test_get_odata_multiple_pages(client): items.append(item) assert len(items) == 10 + @pytest.mark.asyncio async def test_get_multiple_pages_retry_first(client): pages = client.paging.get_multiple_pages_retry_first() @@ -142,6 +149,7 @@ async def test_get_multiple_pages_retry_first(client): items.append(item) assert len(items) == 10 + @pytest.mark.asyncio async def test_get_multiple_pages_retry_second(client): pages = client.paging.get_multiple_pages_retry_second() @@ -150,6 +158,7 @@ async def test_get_multiple_pages_retry_second(client): items.append(item) assert len(items) == 10 + @pytest.mark.asyncio async def test_get_multiple_pages_with_offset(client): pages = client.paging.get_multiple_pages_with_offset(offset=100) @@ -159,6 +168,7 @@ async def test_get_multiple_pages_with_offset(client): assert len(items) == 10 assert items[-1]["properties"]["id"] == 110 + @pytest.mark.asyncio async def test_get_single_pages_failure(client): pages = client.paging.get_single_pages_failure() @@ -166,6 +176,7 @@ async def test_get_single_pages_failure(client): async for i in pages: ... + @pytest.mark.asyncio async def test_get_multiple_pages_failure(client): pages = client.paging.get_multiple_pages_failure() @@ -173,6 +184,7 @@ async def test_get_multiple_pages_failure(client): async for i in pages: ... + @pytest.mark.asyncio async def test_get_multiple_pages_failure_uri(client): pages = client.paging.get_multiple_pages_failure_uri() @@ -180,6 +192,7 @@ async def test_get_multiple_pages_failure_uri(client): async for i in pages: ... + @pytest.mark.asyncio async def test_paging_fragment_path(client): @@ -193,6 +206,7 @@ async def test_paging_fragment_path(client): # Be sure this method is not generated (Transform work) await client.paging.get_multiple_pages_fragment_next_link_next() # pylint: disable=E1101 + @pytest.mark.asyncio async def test_custom_url_get_pages_partial_url(custom_url_client): pages = custom_url_client.paging.get_pages_partial_url("local") @@ -204,6 +218,7 @@ async def test_custom_url_get_pages_partial_url(custom_url_client): assert items[0]["properties"]["id"] == 1 assert items[1]["properties"]["id"] == 2 + @pytest.mark.asyncio async def test_custom_url_get_pages_partial_url_operation(custom_url_client): pages = custom_url_client.paging.get_pages_partial_url_operation("local") @@ -215,11 +230,12 @@ async def test_custom_url_get_pages_partial_url_operation(custom_url_client): assert items[0]["properties"]["id"] == 1 assert items[1]["properties"]["id"] == 2 + @pytest.mark.asyncio async def test_get_multiple_pages_lro(client): - """LRO + Paging at the same time. - """ + """LRO + Paging at the same time.""" from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling + poller = await client.paging.begin_get_multiple_pages_lro(polling=AsyncARMPolling(timeout=0, request_id="test")) pager = await poller.result() items = [] @@ -230,6 +246,7 @@ async def test_get_multiple_pages_lro(client): assert items[0]["properties"]["id"] == 1 assert items[1]["properties"]["id"] == 2 + @pytest.mark.asyncio async def test_initial_response_no_items(client): pages = client.paging.first_response_empty() @@ -238,6 +255,7 @@ async def test_initial_response_no_items(client): items.append(item) assert len(items) == 1 + @pytest.mark.asyncio async def test_item_name_with_xms_client_name(client): pages = client.paging.get_paging_model_with_item_name_with_xms_client_name() @@ -246,6 +264,7 @@ async def test_item_name_with_xms_client_name(client): items.append(item) assert len(items) == 1 + @pytest.mark.asyncio async def test_duplicate_params(client): pages = [p async for p in client.paging.duplicate_params(filter="foo")] @@ -253,10 +272,12 @@ async def test_duplicate_params(client): assert pages[0]["properties"]["id"] == 1 assert pages[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_dont_send_maxpagesize(client): [p async for p in client.paging.page_with_max_page_size()] + @pytest.mark.asyncio async def test_append_api_version(client): pages = [p async for p in client.paging.append_api_version()] @@ -264,6 +285,7 @@ async def test_append_api_version(client): assert pages[0]["properties"]["id"] == 1 assert pages[0]["properties"]["name"] == "Product" + @pytest.mark.asyncio async def test_replace_api_version(client): pages = [p async for p in client.paging.replace_api_version()] diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_parameter.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_parameter.py index d15200cef1c..cdf87112cbe 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_parameter.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_parameter.py @@ -32,15 +32,18 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestParameterGroupingTestService() as client: await yield_(client) + @pytest.fixture def valid_subscription(): - return '1234-5678-9012-3456' + return "1234-5678-9012-3456" + @pytest.fixture @async_generator @@ -50,30 +53,35 @@ async def azure_client(valid_subscription, credential, authentication_policy): ) as client: await yield_(client) + @pytest.fixture def body_parameter(): return 1234 + @pytest.fixture def header_parameter(): - return 'header' + return "header" + @pytest.fixture def query_parameter(): return 21 + @pytest.fixture def path_parameter(): - return 'path' + return "path" @pytest.fixture def unencoded_path(): - return 'path1/path2/path3' + return "path1/path2/path3" + @pytest.fixture def unencoded_query(): - return 'value1&q2=value2&q3=value3' + return "value1&q2=value2&q3=value3" @pytest.mark.asyncio @@ -85,13 +93,11 @@ async def test_post_all_required_parameters(client, body_parameter, header_param custom_header=header_parameter, ) + @pytest.mark.asyncio async def test_post_required_parameters_null_optional_parameters(client, body_parameter, path_parameter): - await client.parameter_grouping.post_required( - path_parameter, - body_parameter, - query=None - ) + await client.parameter_grouping.post_required(path_parameter, body_parameter, query=None) + @pytest.mark.asyncio async def test_post_required_parameters_with_null_required_property(client, path_parameter): @@ -102,6 +108,7 @@ async def test_post_required_parameters_with_null_required_property(client, path with pytest.raises(TypeError): await client.parameter_grouping.post_required() + @pytest.mark.asyncio async def test_post_all_optional(client, header_parameter, query_parameter): await client.parameter_grouping.post_optional( @@ -109,10 +116,12 @@ async def test_post_all_optional(client, header_parameter, query_parameter): query=query_parameter, ) + @pytest.mark.asyncio async def test_post_none_optional(client): await client.parameter_grouping.post_optional(query=None) + @pytest.mark.asyncio async def test_post_all_multi_param_groups(client, header_parameter, query_parameter): await client.parameter_grouping.post_multi_param_groups( @@ -122,6 +131,7 @@ async def test_post_all_multi_param_groups(client, header_parameter, query_param query_two=42, ) + @pytest.mark.asyncio async def test_post_some_multi_param_groups(client, header_parameter): await client.parameter_grouping.post_multi_param_groups( @@ -129,14 +139,17 @@ async def test_post_some_multi_param_groups(client, header_parameter): query_two=42, ) + @pytest.mark.asyncio async def test_post_shared_parameter_group_object(client, header_parameter): await client.parameter_grouping.post_shared_parameter_group_object(header_one=header_parameter) + @pytest.mark.asyncio async def test_post_reserved_words(client): await client.parameter_grouping.post_reserved_words(from_parameter="bob", accept_parameter="yes") + @pytest.mark.asyncio async def test_subscription_in_credentials(azure_client): # valid_api_version = '2.0' @@ -145,6 +158,7 @@ async def test_subscription_in_credentials(azure_client): await azure_client.subscription_in_credentials.post_path_global_valid() await azure_client.subscription_in_credentials.post_swagger_global_valid() + @pytest.mark.asyncio async def test_subscription_in_method(azure_client, valid_subscription): await azure_client.subscription_in_method.post_method_local_valid(valid_subscription) @@ -153,6 +167,7 @@ async def test_subscription_in_method(azure_client, valid_subscription): with pytest.raises(ValueError): await azure_client.subscription_in_method.post_method_local_null(None) + @pytest.mark.asyncio async def test_api_version_default(azure_client): await azure_client.api_version_default.get_method_global_not_provided_valid() @@ -160,6 +175,7 @@ async def test_api_version_default(azure_client): await azure_client.api_version_default.get_path_global_valid() await azure_client.api_version_default.get_swagger_global_valid() + @pytest.mark.asyncio async def test_api_version_local(azure_client): await azure_client.api_version_local.get_method_local_valid() @@ -167,6 +183,7 @@ async def test_api_version_local(azure_client): await azure_client.api_version_local.get_path_local_valid() await azure_client.api_version_local.get_swagger_local_valid() + @pytest.mark.asyncio async def test_skip_url_encoding(azure_client, unencoded_path, unencoded_query): await azure_client.skip_url_encoding.get_method_path_valid(unencoded_path) @@ -178,10 +195,12 @@ async def test_skip_url_encoding(azure_client, unencoded_path, unencoded_query): await azure_client.skip_url_encoding.get_method_query_null() await azure_client.skip_url_encoding.get_method_query_null(q1=None) + @pytest.mark.asyncio async def test_azure_odata(azure_client): await azure_client.odata.get_with_filter(filter="id gt 5 and name eq 'foo'", top=10, orderby="id") + @pytest.mark.asyncio async def test_group_with_constant(client): await client.parameter_grouping.group_with_constant(grouped_constant="foo", grouped_parameter="bar") diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_xms.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_xms.py index b67700b7302..4acb0dbea37 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_xms.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/asynctests/test_xms.py @@ -64,25 +64,34 @@ async def test_client_request_id_in_exception(client): with pytest.raises(HttpResponseError): await client.xms_client_request_id.get() + @pytest.mark.asyncio async def test_xms_request_client_id_in_client_none(client): # expectedRequestId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0' await client.xms_client_request_id.get(request_id=None) + @pytest.mark.asyncio async def test_xms_request_client_id_in_client(client): await client.xms_client_request_id.get(request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + @pytest.mark.asyncio async def test_xms_request_client_overwrite_via_parameter(client_no_request_id): # We DON'T support a Swagger parameter for request_id, the request_id policy will overwrite it. # We disable the request_id policy for this test - await client_no_request_id.xms_client_request_id.param_get(headers={"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"}) + await client_no_request_id.xms_client_request_id.param_get( + headers={"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} + ) + @pytest.mark.asyncio async def test_xms_custom_named_request_id(client): await client.header.custom_named_request_id(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + @pytest.mark.asyncio async def test_xms_custom_named_request_id_parameter_group(client): - await client.header.custom_named_request_id_param_grouping(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + await client.header.custom_named_request_id_param_grouping( + foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0" + ) diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/conftest.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/conftest.py index 222d7fdebfe..6b2ca89b0c7 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/conftest.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/conftest.py @@ -38,21 +38,26 @@ cwd = dirname(realpath(__file__)) -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def start_server_process(): - cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format(cwd) - if os.name == 'nt': #On windows, subprocess creation works without being in the shell + cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format( + cwd + ) + if os.name == "nt": # On windows, subprocess creation works without being in the shell return subprocess.Popen(cmd) - return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) #On linux, have to set shell=True + return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # On linux, have to set shell=True + -#Ideally this would be in a common helper library shared between the tests +# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session") def testserver(): """Start the Autorest testserver.""" @@ -77,6 +82,7 @@ def on_response(self, request, response, **kwargs): if "Set-Cookie" in http_response.headers: self._current_cookie = http_response.headers["Set-Cookie"] + @pytest.fixture() def cookie_policy(): return CookiePolicy() @@ -87,11 +93,15 @@ def credential(): """I actually don't need anything, since the authentication policy will bypass it. """ + class FakeCredential: pass + return FakeCredential() + @pytest.fixture() def authentication_policy(): from azure.core.pipeline.policies import SansIOHTTPPolicy - return SansIOHTTPPolicy() \ No newline at end of file + + return SansIOHTTPPolicy() diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/serializer.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/serializer.py index d96a0bb9dec..d3b815d5e4b 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/serializer.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/serializer.py @@ -34,6 +34,7 @@ try: from datetime import timezone as _FixedOffset except ImportError: # Python 2.7 + class _FixedOffset(datetime.tzinfo): # type: ignore """Fixed offset in minutes east from UTC. Copy/pasted from Python doc @@ -47,7 +48,7 @@ def utcoffset(self, dt): return self.__offset def tzname(self, dt): - return str(self.__offset.total_seconds()/3600) + return str(self.__offset.total_seconds() / 3600) def __repr__(self): return "".format(self.tzname(None)) @@ -58,6 +59,7 @@ def dst(self, dt): def __getinitargs__(self): return (self.__offset,) + class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" @@ -73,37 +75,53 @@ def dst(self, dt): """No daylight saving for UTC.""" return datetime.timedelta(hours=1) + try: from datetime import timezone + TZ_UTC = timezone.utc # type: ignore except ImportError: TZ_UTC = UTC() # type: ignore -DAYS = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", - 4: "Fri", 5: "Sat", 6: "Sun"} -MONTHS = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", - 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} +DAYS = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} +MONTHS = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", +} + +VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") -VALID_DATE = re.compile( - r'\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}' - r'\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?') def serialize_base64(attr): - encoded = b64encode(attr).decode('ascii') - return encoded.strip('=').replace('+', '-').replace('/', '_') + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + def deserialize_base64(attr): - padding = '=' * (3 - (len(attr) + 3) % 4) + padding = "=" * (3 - (len(attr) + 3) % 4) attr = attr + padding - encoded = attr.replace('-', '+').replace('_', '/') + encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) + def deserialize_date(attr): return isodate.parse_date(attr) + def deserialize_datetime(attr): return isodate.parse_datetime(attr) + def serialize_rfc(attr): try: utc = attr.utctimetuple() @@ -111,11 +129,10 @@ def serialize_rfc(attr): raise TypeError("RFC1123 object must be valid Datetime object.") return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - DAYS[utc.tm_wday], utc.tm_mday, - MONTHS[utc.tm_mon], utc.tm_year, - utc.tm_hour, utc.tm_min, utc.tm_sec + DAYS[utc.tm_wday], utc.tm_mday, MONTHS[utc.tm_mon], utc.tm_year, utc.tm_hour, utc.tm_min, utc.tm_sec ) + def serialize_iso(attr): if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -123,13 +140,14 @@ def serialize_iso(attr): if utc.tm_year > 9999 or utc.tm_year < 1: raise OverflowError("Hit max or min date") - microseconds = str(attr.microsecond).rjust(6,'0').rstrip('0').ljust(3, '0') + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") if microseconds: - microseconds = '.'+microseconds + microseconds = "." + microseconds date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, - utc.tm_hour, utc.tm_min, utc.tm_sec) - return date + microseconds + 'Z' + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + def deserialize_iso(attr): if isinstance(attr, ET.Element): @@ -139,7 +157,7 @@ def deserialize_iso(attr): if not match: raise ValueError("Invalid datetime string: " + attr) - check_decimal = attr.split('.') + check_decimal = attr.split(".") if len(check_decimal) > 1: decimal_str = "" for digit in check_decimal[1]: @@ -156,61 +174,70 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") return date_obj + def deserialize_bytearray(attr): if isinstance(attr, ET.Element): attr = attr.text return bytearray(b64decode(attr)) + def serialize_bytearray(attr): return b64encode(attr).decode() + def serialize_date(attr): if isinstance(attr, str): attr = isodate.parse_date(attr) t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) return t + def deserialize_duration(attr): if isinstance(attr, ET.Element): attr = attr.text return isodate.parse_duration(attr) + def serialize_duration(attr): if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + def deserialize_rfc(attr): if isinstance(attr, ET.Element): attr = attr.text parsed_date = email.utils.parsedate_tz(attr) date_obj = datetime.datetime( - *parsed_date[:6], - tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0)/60)) + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) return date_obj + def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) return datetime.datetime.fromtimestamp(attr, TZ_UTC) + def serialize_unix(attr): if isinstance(attr, int): return attr return int(calendar.timegm(attr.utctimetuple())) + def deserialize_time(attr): if isinstance(attr, ET.Element): attr = attr.text return isodate.parse_time(attr) + def serialize_time(attr): if isinstance(attr, str): attr = isodate.parse_time(attr) t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) if attr.microsecond: t += ".{:02}".format(attr.microsecond) - return t \ No newline at end of file + return t diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_custom_base_uri.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_custom_base_uri.py index b1d26f6b43a..a4dc78cc489 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_custom_base_uri.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_custom_base_uri.py @@ -30,6 +30,7 @@ import pytest + @pytest.fixture def client(): with AutoRestParameterizedHostTestClient(host="host:3000") as client: @@ -40,14 +41,17 @@ def client(): def test_custom_base_uri_positive(client): client.paths.get_empty("local") + def test_custom_base_uri_get_empty(client): with pytest.raises(ServiceRequestError): client.paths.get_empty("bad") + def test_custom_base_uri_get_none(client): with pytest.raises(ValueError): client.paths.get_empty(None) + def test_custom_base_uri_bad_host(client): client._config.host = "badhost:3000" with pytest.raises(ServiceRequestError): diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_url.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_url.py index 6ff3604097f..2910ca07b9c 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_url.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_azure_url.py @@ -34,5 +34,5 @@ def test_azure_url(credential, authentication_policy): with MicrosoftAzureTestUrl(credential, sub_id, authentication_policy=authentication_policy) as client: group = client.group.get_sample_resource_group("testgoup101") - assert group['name'] == "testgroup101" - assert group['location'] == "West US" + assert group["name"] == "testgroup101" + assert group["location"] == "West US" diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_config.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_config.py index e9064a074d7..435c1de8751 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_config.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_config.py @@ -25,27 +25,33 @@ # -------------------------------------------------------------------------- from azure.mgmt.core.policies import ARMHttpLoggingPolicy + # Head is azure-arm from headversiontolerant import AutoRestHeadTestService + def test_arm_http_logging_policy_default(credential): with AutoRestHeadTestService(credential) as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + def test_arm_http_logging_policy_custom(credential): http_logging_policy = ARMHttpLoggingPolicy(base_url="test") http_logging_policy = ARMHttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) with AutoRestHeadTestService(credential, http_logging_policy=http_logging_policy) as client: assert isinstance(client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) + def test_credential_scopes_default(credential): with AutoRestHeadTestService(credential) as client: - assert client._config.credential_scopes == ['https://management.azure.com/.default'] + assert client._config.credential_scopes == ["https://management.azure.com/.default"] + def test_credential_scopes_override(credential): with AutoRestHeadTestService(credential, credential_scopes=["http://i-should-be-the-only-credential"]) as client: diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_custom_poller_pager.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_custom_poller_pager.py index 17e7bcf7fc6..26a06fddf87 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_custom_poller_pager.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_custom_poller_pager.py @@ -28,15 +28,18 @@ import pytest + @pytest.fixture def client(credential, authentication_policy): with AutoRestPagingTestService(credential, authentication_policy=authentication_policy) as client: yield client + def test_custom_pager(client): pager = client.paging.get_single_pages() assert isinstance(pager, CustomPager) + def test_custom_poller(client): poller = client.paging.begin_get_multiple_pages_lro() - assert isinstance(poller, CustomPoller) \ No newline at end of file + assert isinstance(poller, CustomPoller) diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_duration.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_duration.py index 43e1ff38c52..eb57933aafc 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_duration.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_duration.py @@ -31,17 +31,20 @@ import pytest + @pytest.fixture def client(): with AutoRestDurationTestService() as client: yield client + def test_get_null_and_invalid(client): assert client.duration.get_null() is None with pytest.raises(isodate.ISO8601Error): deserialize_duration(client.duration.get_invalid()) + def test_positive_duration(client): client.duration.get_positive_duration() delta = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_head.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_head.py index 694479064e9..0972e4fa315 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_head.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_head.py @@ -30,6 +30,7 @@ import pytest + def test_head(credential, authentication_policy): with AutoRestHeadTestService(credential, authentication_policy=authentication_policy) as client: @@ -38,6 +39,7 @@ def test_head(credential, authentication_policy): assert client.http_success.head204() assert not client.http_success.head404() + def test_head_exception(credential, authentication_policy): with AutoRestHeadExceptionTestService(credential, authentication_policy=authentication_policy) as client: diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro.py index fd451c5ad88..100a8a38aaf 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro.py @@ -42,6 +42,7 @@ POLLING_INTERVAL = 0 + class AutorestTestARMPolling(ARMPolling): def _polling_cookie(self, response): @@ -52,38 +53,39 @@ def _polling_cookie(self, response): otherwise an empty dictionary. """ parsed_url = urlparse(response.request.url) - host = parsed_url.hostname.strip('.') - if host == 'localhost': - return {'cookie': response.headers.get('set-cookie', '')} + host = parsed_url.hostname.strip(".") + if host == "localhost": + return {"cookie": response.headers.get("set-cookie", "")} return {} def request_status(self, status_link): request = HttpRequest("GET", status_link, headers=self._polling_cookie(self._pipeline_response.http_response)) # ARM requires to re-inject 'x-ms-client-request-id' while polling - if 'request_id' not in self._operation_config: - self._operation_config['request_id'] = self._get_request_id() + if "request_id" not in self._operation_config: + self._operation_config["request_id"] = self._get_request_id() return self._client._pipeline.run(request, stream=False, **self._operation_config) + @pytest.fixture() def client(cookie_policy, credential): """Create a AutoRestLongRunningOperationTestService client with test server credentials.""" - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - RetryPolicy(), - cookie_policy - ] - - with AutoRestLongRunningOperationTestService(credential=credential, policies=policies, polling_interval=POLLING_INTERVAL) as client: + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), RetryPolicy(), cookie_policy] + + with AutoRestLongRunningOperationTestService( + credential=credential, policies=policies, polling_interval=POLLING_INTERVAL + ) as client: yield client + @pytest.fixture() def product(): return {"location": "West US"} + + @pytest.fixture() def custom_headers(): - return {"x-ms-client-request-id": '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'} + return {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} + def assert_raises_with_message(msg, func, *args, **kwargs): try: @@ -92,7 +94,7 @@ def assert_raises_with_message(msg, func, *args, **kwargs): except HttpResponseError as err: assert err.response is not None - print("BODY: "+err.response.text()) + print("BODY: " + err.response.text()) try: msg, internal_msg = msg @@ -109,233 +111,275 @@ def assert_raises_with_message(msg, func, *args, **kwargs): if internal_msg: assert internal_msg in str(err.inner_exception) + def lro_result(func, *args, **kwargs): if "polling" not in kwargs: kwargs["polling"] = AutorestTestARMPolling(0) return func(*args, **kwargs).result() + def test_post_double_headers_final_continuation_token(client): poller = client.lros.begin_post_double_headers_final_location_get() continuation_token = poller.continuation_token() poller = client.lros.begin_post_double_headers_final_location_get(continuation_token=continuation_token) product = poller.result() - assert product['id'] == "100" + assert product["id"] == "100" + def test_post_double_headers_final(client): product = client.lros.begin_post_double_headers_final_location_get().result() - assert product['id'] == "100" + assert product["id"] == "100" product = client.lros.begin_post_double_headers_final_azure_header_get().result() - assert product['id'] == "100" + assert product["id"] == "100" + def test_post_double_headers_default(client): # This test will work as long as the default is Location product = client.lros.begin_post_double_headers_final_azure_header_get_default().result() - assert product['id'] == "100" + assert product["id"] == "100" + def test_happy_put201_creating_succeeded200(client, product): process = lro_result(client.lros.begin_put201_creating_succeeded200, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] # Testing nopolling process = lro_result(client.lros.begin_put201_creating_succeeded200, product, polling=False) - assert "Creating" == process["properties"]['provisioningState'] + assert "Creating" == process["properties"]["provisioningState"] + def test_happy_put201_creating_failed200(client, product): assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put201_creating_failed200, product) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_put201_creating_failed200, product + ) process = lro_result(client.lros.begin_put201_creating_failed200, product, polling=False) - assert "Created" == process["properties"]['provisioningState'] + assert "Created" == process["properties"]["provisioningState"] + def test_happy_put200_updating_succeeded204(client, product): process = lro_result(client.lros.begin_put200_updating_succeeded204, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = lro_result(client.lros.begin_put200_updating_succeeded204, product, polling=False) - assert "Updating" == process["properties"]['provisioningState'] + assert "Updating" == process["properties"]["provisioningState"] + def test_happy_put200_acceptedcanceled200(client, product): assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put200_acceptedcanceled200, product) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_put200_acceptedcanceled200, product + ) process = lro_result(client.lros.begin_put200_acceptedcanceled200, product, polling=False) - assert "Accepted" == process["properties"]['provisioningState'] + assert "Accepted" == process["properties"]["provisioningState"] + def test_happy_put_no_header_in_retry(client, product): process = lro_result(client.lros.begin_put_no_header_in_retry, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = lro_result(client.lros.begin_put_async_no_header_in_retry, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + def test_happy_put_sub_resource(client): process = lro_result(client.lros.begin_put_sub_resource, {}) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = lro_result(client.lros.begin_put_async_sub_resource, {}) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + def test_happy_put_non_resource(client): process = lro_result(client.lros.begin_put_non_resource, {}) - assert "100" == process['id'] + assert "100" == process["id"] process = lro_result(client.lros.begin_put_async_non_resource, {}) - assert "100" == process['id'] + assert "100" == process["id"] + def test_happy_put200_succeeded(client, product): process = lro_result(client.lros.begin_put200_succeeded, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = lro_result(client.lros.begin_put200_succeeded_no_state, product) - assert "100" == process['id'] + assert "100" == process["id"] + def test_put201_succeeded(client, product): process = lro_result(client.lros.begin_put201_succeeded, product) - assert "Succeeded" == process["properties"]['provisioningState'] - assert "100" == process['id'] + assert "Succeeded" == process["properties"]["provisioningState"] + assert "100" == process["id"] assert "foo" == process["name"] + def test_happy_put202_retry200(client, product): process = lro_result(client.lros.begin_put202_retry200, product) - assert "100" == process['id'] + assert "100" == process["id"] + def test_happy_put_retry_succeeded(client, product): process = lro_result(client.lros.begin_put_async_retry_succeeded, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = lro_result(client.lros.begin_put_async_no_retry_succeeded, product) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + def test_happy_put_retry_failed_canceled(client, product): assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_put_async_retry_failed, product) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_put_async_retry_failed, product + ) assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_put_async_no_retrycanceled, product) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_put_async_no_retrycanceled, product + ) + def test_post202_retry200(client, product): process = lro_result(client.lros.begin_post202_retry200, product) assert process is None + def test_happy_delete(client): assert lro_result(client.lros.begin_delete204_succeeded) is None assert lro_result(client.lros.begin_delete202_retry200) is None assert lro_result(client.lros.begin_delete202_no_retry204) is None + def test_happy_delete_no_header_in_retry(client): assert lro_result(client.lros.begin_delete_no_header_in_retry) is None assert lro_result(client.lros.begin_delete_async_no_header_in_retry) is None + def test_happy_delete_async_retry_failed_canceled(client): assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_delete_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_delete_async_retrycanceled + ) assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "failed"), - client.lros.begin_delete_async_retry_failed) + ("Operation returned an invalid status 'OK'", "failed"), client.lros.begin_delete_async_retry_failed + ) + def test_happy_delete_async_succeeded(client): assert lro_result(client.lros.begin_delete_async_no_retry_succeeded) is None assert lro_result(client.lros.begin_delete_async_retry_succeeded) is None + def test_happy_delete_provisioning(client): process = lro_result(client.lros.begin_delete_provisioning202_accepted200_succeeded) - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] result = lro_result(client.lros.begin_delete_provisioning202_deletingcanceled200) - assert result["properties"]['provisioningState'] == 'Canceled' + assert result["properties"]["provisioningState"] == "Canceled" result = lro_result(client.lros.begin_delete_provisioning202_deleting_failed200) - assert result["properties"]['provisioningState'] == 'Failed' + assert result["properties"]["provisioningState"] == "Failed" + def test_happy_post(client, product): assert lro_result(client.lros.begin_post202_no_retry204, product) is None sku = lro_result(client.lros.begin_post200_with_payload) - assert sku['id'] == '1' + assert sku["id"] == "1" + def test_happy_post_async_retry_failed_canceled(client, product): - assert_raises_with_message("Internal Server Error", - client.lros.begin_post_async_retry_failed) + assert_raises_with_message("Internal Server Error", client.lros.begin_post_async_retry_failed) assert_raises_with_message( - ("Operation returned an invalid status 'OK'", "canceled"), - client.lros.begin_post_async_retrycanceled) + ("Operation returned an invalid status 'OK'", "canceled"), client.lros.begin_post_async_retrycanceled + ) + def test_happy_post_async_succeeded(client, product): prod = lro_result(client.lros.begin_post_async_retry_succeeded) - assert prod['id'] == "100" + assert prod["id"] == "100" prod = lro_result(client.lros.begin_post_async_no_retry_succeeded) - assert prod['id'] == "100" + assert prod["id"] == "100" + def test_retrys_put(client, product): process = lro_result(client.lro_retrys.begin_put201_creating_succeeded200, product) - assert 'Succeeded' == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] process = lro_result(client.lro_retrys.begin_put_async_relative_retry_succeeded, product) - assert 'Succeeded' == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + def test_retrys_delete(client, product): process = lro_result(client.lro_retrys.begin_delete_provisioning202_accepted200_succeeded) - assert 'Succeeded' == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] assert lro_result(client.lro_retrys.begin_delete202_retry200) is None assert lro_result(client.lro_retrys.begin_delete_async_relative_retry_succeeded) is None + def test_retrys_post(client, product): assert lro_result(client.lro_retrys.begin_post202_retry200, product) is None assert lro_result(client.lro_retrys.begin_post_async_relative_retry_succeeded, product) is None + def test_custom_headers_put_async_retry_succeeded(client, product, custom_headers): process = lro_result(client.lr_os_custom_header.begin_put_async_retry_succeeded, product, headers=custom_headers) assert process is not None + def test_custom_headers_post_async_retry_succeeded(client, product, custom_headers): process = lro_result(client.lr_os_custom_header.begin_post_async_retry_succeeded, product, headers=custom_headers) assert process is None + def test_custom_headers_put201_creating_succeeded200(client, product, custom_headers): process = lro_result(client.lr_os_custom_header.begin_put201_creating_succeeded200, product, headers=custom_headers) assert process is not None + def test_custom_headers_post202_retry200(client, product, custom_headers): process = lro_result(client.lr_os_custom_header.begin_post202_retry200, product, headers=custom_headers) assert process is None + def test_sads_put_non_retry(client, product): - assert_raises_with_message("Bad Request", - client.lrosads.begin_put_non_retry400, product) + assert_raises_with_message("Bad Request", client.lrosads.begin_put_non_retry400, product) + + assert_raises_with_message("Error from the server", client.lrosads.begin_put_non_retry201_creating400, product) - assert_raises_with_message("Error from the server", - client.lrosads.begin_put_non_retry201_creating400, product) def test_sads_put_async_relative(client, product): - assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.lrosads.begin_put_async_relative_retry400, product) + assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", client.lrosads.begin_put_async_relative_retry400, product + ) - assert_raises_with_message("no status found in body", - client.lrosads.begin_put_async_relative_retry_no_status, product) + assert_raises_with_message( + "no status found in body", client.lrosads.begin_put_async_relative_retry_no_status, product + ) + + assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_async_relative_retry_no_status_payload, + product, + ) - assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_async_relative_retry_no_status_payload, product) def test_sads_put_error201_no_provisioning_state_payload(client, product): - assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_put_error201_no_provisioning_state_payload, product) + assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_put_error201_no_provisioning_state_payload, + product, + ) + def test_sads_put200_invalid_json_with_exception(client, product): with pytest.raises(DecodeError): lro_result(client.lrosads.begin_put200_invalid_json, product) + def test_sads_put_async_relative_with_exception(client, product): with pytest.raises(DecodeError): lro_result(client.lrosads.begin_put_async_relative_retry_invalid_json_polling, product) @@ -343,28 +387,29 @@ def test_sads_put_async_relative_with_exception(client, product): with pytest.raises(Exception): lro_result(client.lrosads.begin_put_async_relative_retry_invalid_header, product) + def test_sads_put_non_retry201_creating400_invalid_json_with_exception(client, product): with pytest.raises(DecodeError): lro_result(client.lrosads.begin_put_non_retry201_creating400_invalid_json, product) + def tests_lro_sads_delete_non_retry(client, product): - assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_non_retry400) + assert_raises_with_message("Bad Request", client.lrosads.begin_delete_non_retry400) + + assert_raises_with_message("Bad Request", client.lrosads.begin_delete202_non_retry400) - assert_raises_with_message("Bad Request", - client.lrosads.begin_delete202_non_retry400) def test_sads_delete_async_relative(client, product): - assert_raises_with_message("Bad Request", - client.lrosads.begin_delete_async_relative_retry400) + assert_raises_with_message("Bad Request", client.lrosads.begin_delete_async_relative_retry400) + + assert_raises_with_message("no status found in body", client.lrosads.begin_delete_async_relative_retry_no_status) - assert_raises_with_message("no status found in body", - client.lrosads.begin_delete_async_relative_retry_no_status) def test_sads_delete204_succeeded(client): lro_result(client.lrosads.begin_delete204_succeeded) + def test_sads_delete_async_relative_with_exception(client): with pytest.raises(Exception): lro_result(client.lrosads.begin_delete_async_relative_retry_invalid_header) @@ -372,23 +417,26 @@ def test_sads_delete_async_relative_with_exception(client): with pytest.raises(DecodeError): lro_result(client.lrosads.begin_delete_async_relative_retry_invalid_json_polling) + def test_sads_delete202_retry_invalid_header_with_exception(client): with pytest.raises(Exception): lro_result(client.lrosads.begin_delete202_retry_invalid_header) + def test_sads_post_non_retry(client, product): - assert_raises_with_message("Bad Request", - client.lrosads.begin_post_non_retry400, product) + assert_raises_with_message("Bad Request", client.lrosads.begin_post_non_retry400, product) + + assert_raises_with_message("Bad Request", client.lrosads.begin_post202_non_retry400, product) - assert_raises_with_message("Bad Request", - client.lrosads.begin_post202_non_retry400, product) def test_sads_post_async_relative(client, product): - assert_raises_with_message("Bad Request", - client.lrosads.begin_post_async_relative_retry400, product) + assert_raises_with_message("Bad Request", client.lrosads.begin_post_async_relative_retry400, product) + + assert_raises_with_message( + "The response from long running operation does not contain a body.", + client.lrosads.begin_post_async_relative_retry_no_payload, + ) - assert_raises_with_message("The response from long running operation does not contain a body.", - client.lrosads.begin_post_async_relative_retry_no_payload) def test_sads_post202_no_location(client): # Testserver wants us to fail (coverage name is LROErrorPostNoLocation) @@ -397,6 +445,7 @@ def test_sads_post202_no_location(client): process = lro_result(client.lrosads.begin_post202_no_location) assert process is None + def test_sads_post_async_relative_with_exception(client): with pytest.raises(Exception): lro_result(client.lrosads.begin_post_async_relative_retry_invalid_header) @@ -404,9 +453,11 @@ def test_sads_post_async_relative_with_exception(client): with pytest.raises(DecodeError): lro_result(client.lrosads.begin_post_async_relative_retry_invalid_json_polling) + def test_post202_retry_invalid_header_with_exception(client): with pytest.raises(Exception): - lro_result(client.lrosads.begin_post202_retry_invalid_header) + lro_result(client.lrosads.begin_post202_retry_invalid_header) + def test_polling_interval_operation(client): default_polling_interval_start_time = time.time() @@ -421,6 +472,7 @@ def test_polling_interval_operation(client): assert product1 == product2 + def test_polling_interval_config(cookie_policy, credential, client): default_polling_interval_start_time = time.time() product1 = client.lros.begin_post_double_headers_final_azure_header_get_default().result() @@ -428,35 +480,43 @@ def test_polling_interval_config(cookie_policy, credential, client): assert abs(default_polling_interval_duration - 0) < 3 # Now we create a new client with a polling_interval of 1 - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - RetryPolicy(), - cookie_policy - ] - client_one_second = AutoRestLongRunningOperationTestService(credential=credential, policies=policies, polling_interval=1) + policies = [RequestIdPolicy(), HeadersPolicy(), ContentDecodePolicy(), RetryPolicy(), cookie_policy] + client_one_second = AutoRestLongRunningOperationTestService( + credential=credential, policies=policies, polling_interval=1 + ) one_second_polling_interval_start_time = time.time() product2 = client_one_second.lros.begin_post_double_headers_final_azure_header_get_default().result() one_second_polling_interval_duration = time.time() - one_second_polling_interval_start_time assert abs(one_second_polling_interval_duration - 1) < 3 assert product1 == product2 + def test_passing_kwargs(client, product): process = lro_result(client.lros.begin_put200_succeeded, product, content_type="application/json") - assert "Succeeded" == process["properties"]['provisioningState'] + assert "Succeeded" == process["properties"]["provisioningState"] + def test_lro_list(client, product): products = lro_result(client.lros.begin_post202_list) assert len(products) == 1 product = products[0] - assert product['id'] == "100" + assert product["id"] == "100" assert product["name"] == "foo" + def test_patch201_retry_with_async_header(client, product): product = lro_result(client.lros.begin_patch201_retry_with_async_header, product) - assert product == {"properties": {"provisioningState": "Succeeded"}, "id": "/lro/patch/201/retry/onlyAsyncHeader", "name": "foo"} + assert product == { + "properties": {"provisioningState": "Succeeded"}, + "id": "/lro/patch/201/retry/onlyAsyncHeader", + "name": "foo", + } + def test_patch202_retry_with_async_and_location_header(client, product): product = lro_result(client.lros.begin_patch202_retry_with_async_and_location_header, product) - assert product == { "properties": { "provisioningState": "Succeeded"}, "id": "/lro/patch/202/retry/asyncAndLocationHeader", "name": "foo" } + assert product == { + "properties": {"provisioningState": "Succeeded"}, + "id": "/lro/patch/202/retry/asyncAndLocationHeader", + "name": "foo", + } diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_paging.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_paging.py index 3a20ba9defa..9caa985a4f9 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_paging.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_paging.py @@ -27,13 +27,17 @@ from lropagingversiontolerant import LroPagingClient from azure.core.exceptions import ResourceNotFoundError + @pytest.fixture() def client(): with LroPagingClient() as client: yield client + def test_begin_update_qnas(client): with pytest.raises(ResourceNotFoundError): - paged_result = client.question_answering_projects.begin_update_qnas("project_name", [{"hello": "world"}]).result() + paged_result = client.question_answering_projects.begin_update_qnas( + "project_name", [{"hello": "world"}] + ).result() final_result = list(paged_result) assert len(final_result) == 0 diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_parameterized_endpoints.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_parameterized_endpoints.py index e115492e14a..b0fbbac2aba 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_parameterized_endpoints.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_lro_parameterized_endpoints.py @@ -26,15 +26,18 @@ import pytest from lrowithparameterizedendpointsversiontolerant import LROWithParamaterizedEndpoints + @pytest.fixture def client(credential): with LROWithParamaterizedEndpoints(credential=credential, host="host:3000") as client: yield client + def test_poll_with_parameterized_endpoints(client): - poller = client.begin_poll_with_parameterized_endpoints(account_name='local', polling_interval=0) - assert poller.result() == 'success' + poller = client.begin_poll_with_parameterized_endpoints(account_name="local", polling_interval=0) + assert poller.result() == "success" + def test_poll_with_constant_parameterized_endpoints(client): - poller = client.begin_poll_with_constant_parameterized_endpoints(account_name='local', polling_interval=0) - assert poller.result() == 'success' + poller = client.begin_poll_with_constant_parameterized_endpoints(account_name="local", polling_interval=0) + assert poller.result() == "success" diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_paging.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_paging.py index 36a3b1246fb..4fad5092146 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_paging.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_paging.py @@ -31,6 +31,7 @@ import pytest + @pytest.fixture def client(): with AutoRestPagingTestService() as client: @@ -42,6 +43,7 @@ def custom_url_client(): with AutoRestParameterizedHostTestPagingClient(host="host:3000") as client: yield client + def test_get_no_item_name_pages(client): pages = client.paging.get_no_item_name_pages() items = [i for i in pages] @@ -49,6 +51,7 @@ def test_get_no_item_name_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + def test_get_null_next_link_name_pages(client): pages = client.paging.get_null_next_link_name_pages() items = [i for i in pages] @@ -56,6 +59,7 @@ def test_get_null_next_link_name_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + def test_get_empty_next_link_name_pages(client): pages = client.paging.get_empty_next_link_name_pages() items = [i for i in pages] @@ -63,14 +67,17 @@ def test_get_empty_next_link_name_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + def test_get_single_pages_with_cb(client): def cb(list_of_obj): for obj in list_of_obj: obj["marked"] = True return list_of_obj + pages = client.paging.get_single_pages(cls=cb) assert all(obj["marked"] for obj in pages) + def test_get_single_pages(client): pages = client.paging.get_single_pages() items = [i for i in pages] @@ -78,6 +85,7 @@ def test_get_single_pages(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + def test_get_single_pages_with_body_params(client): pages = client.paging.get_single_pages_with_body_params({"name": "body"}) items = [i for i in pages] @@ -85,31 +93,37 @@ def test_get_single_pages_with_body_params(client): assert items[0]["properties"]["id"] == 1 assert items[0]["properties"]["name"] == "Product" + def test_get_multiple_pages(client): pages = client.paging.get_multiple_pages() items = [i for i in pages] assert len(items) == 10 + def test_query_params(client): - pages = client.paging.get_with_query_params(required_query_parameter='100') + pages = client.paging.get_with_query_params(required_query_parameter="100") items = [i for i in pages] assert len(items) == 2 + def test_get_odata_multiple_pages(client): pages = client.paging.get_odata_multiple_pages() items = [i for i in pages] assert len(items) == 10 + def test_get_multiple_pages_retry_first(client): pages = client.paging.get_multiple_pages_retry_first() items = [i for i in pages] assert len(items) == 10 + def test_get_multiple_pages_retry_second(client): pages = client.paging.get_multiple_pages_retry_second() items = [i for i in pages] assert len(items) == 10 + def test_get_multiple_pages_with_offset(client): pages = client.paging.get_multiple_pages_with_offset(offset=100) items = [i for i in pages] @@ -122,16 +136,19 @@ def test_get_single_pages_failure(client): with pytest.raises(HttpResponseError): list(pages) + def test_get_multiple_pages_failure(client): pages = client.paging.get_multiple_pages_failure() with pytest.raises(HttpResponseError): list(pages) + def test_get_multiple_pages_failure_uri(client): pages = client.paging.get_multiple_pages_failure_uri() with pytest.raises(HttpResponseError): list(pages) + def test_paging_fragment_path(client): pages = client.paging.get_multiple_pages_fragment_next_link(api_version="1.6", tenant="test_user") @@ -142,6 +159,7 @@ def test_paging_fragment_path(client): # Be sure this method is not generated (Transform work) client.paging.get_multiple_pages_fragment_next_link_next() # pylint: disable=E1101 + def test_custom_url_get_pages_partial_url(custom_url_client): paged = list(custom_url_client.paging.get_pages_partial_url("local")) @@ -149,6 +167,7 @@ def test_custom_url_get_pages_partial_url(custom_url_client): assert paged[0]["properties"]["id"] == 1 assert paged[1]["properties"]["id"] == 2 + def test_custom_url_get_pages_partial_url_operation(custom_url_client): paged = list(custom_url_client.paging.get_pages_partial_url_operation("local")) @@ -156,10 +175,11 @@ def test_custom_url_get_pages_partial_url_operation(custom_url_client): assert paged[0]["properties"]["id"] == 1 assert paged[1]["properties"]["id"] == 2 + def test_get_multiple_pages_lro(client): - """LRO + Paging at the same time. - """ + """LRO + Paging at the same time.""" from azure.mgmt.core.polling.arm_polling import ARMPolling + poller = client.paging.begin_get_multiple_pages_lro(polling=ARMPolling(timeout=0, request_id="test")) pager = poller.result() @@ -169,31 +189,37 @@ def test_get_multiple_pages_lro(client): assert items[0]["properties"]["id"] == 1 assert items[1]["properties"]["id"] == 2 + def test_item_name_with_xms_client_name(client): pages = client.paging.get_paging_model_with_item_name_with_xms_client_name() items = [i for i in pages] assert len(items) == 1 + def test_initial_response_no_items(client): pages = client.paging.first_response_empty() items = [i for i in pages] assert len(items) == 1 + def test_duplicate_params(client): pages = list(client.paging.duplicate_params(filter="foo")) assert len(pages) == 1 assert pages[0]["properties"]["id"] == 1 assert pages[0]["properties"]["name"] == "Product" + def test_dont_send_maxpagesize(client): list(client.paging.page_with_max_page_size()) + def test_append_api_version(client): pages = list(client.paging.append_api_version()) assert len(pages) == 1 assert pages[0]["properties"]["id"] == 1 assert pages[0]["properties"]["name"] == "Product" + def test_replace_api_version(client): pages = list(client.paging.replace_api_version()) assert len(pages) == 1 diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_parameter.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_parameter.py index a4e8dd2eaeb..9faea73e72c 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_parameter.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_parameter.py @@ -30,44 +30,54 @@ from azure.core.exceptions import HttpResponseError import pytest + @pytest.fixture def client(): with AutoRestParameterGroupingTestService() as client: yield client + @pytest.fixture def valid_subscription(): - return '1234-5678-9012-3456' + return "1234-5678-9012-3456" + @pytest.fixture def azure_client(valid_subscription, credential, authentication_policy): - with AutoRestAzureSpecialParametersTestClient(credential, valid_subscription, authentication_policy=authentication_policy) as client: + with AutoRestAzureSpecialParametersTestClient( + credential, valid_subscription, authentication_policy=authentication_policy + ) as client: yield client + @pytest.fixture def body_parameter(): return 1234 + @pytest.fixture def header_parameter(): - return 'header' + return "header" + @pytest.fixture def query_parameter(): return 21 + @pytest.fixture def path_parameter(): - return 'path' + return "path" @pytest.fixture def unencoded_path(): - return 'path1/path2/path3' + return "path1/path2/path3" + @pytest.fixture def unencoded_query(): - return 'value1&q2=value2&q3=value3' + return "value1&q2=value2&q3=value3" def test_post_all_required_parameters(client, body_parameter, header_parameter, query_parameter, path_parameter): @@ -78,12 +88,10 @@ def test_post_all_required_parameters(client, body_parameter, header_parameter, custom_header=header_parameter, ) + def test_post_required_parameters_null_optional_parameters(client, body_parameter, path_parameter): - client.parameter_grouping.post_required( - path_parameter, - body_parameter, - query=None - ) + client.parameter_grouping.post_required(path_parameter, body_parameter, query=None) + def test_post_required_parameters_with_null_required_property(client, path_parameter): @@ -93,15 +101,18 @@ def test_post_required_parameters_with_null_required_property(client, path_param with pytest.raises(TypeError): client.parameter_grouping.post_required() + def test_post_all_optional(client, header_parameter, query_parameter): client.parameter_grouping.post_optional( custom_header=header_parameter, query=query_parameter, ) + def test_post_none_optional(client): client.parameter_grouping.post_optional(query=None) + def test_post_all_multi_param_groups(client, header_parameter, query_parameter): client.parameter_grouping.post_multi_param_groups( header_one=header_parameter, @@ -110,18 +121,22 @@ def test_post_all_multi_param_groups(client, header_parameter, query_parameter): query_two=42, ) + def test_post_some_multi_param_groups(client, header_parameter): client.parameter_grouping.post_multi_param_groups( header_one=header_parameter, query_two=42, ) + def test_post_shared_parameter_group_object(client, header_parameter): client.parameter_grouping.post_shared_parameter_group_object(header_one=header_parameter) + def test_post_reserved_words(client): client.parameter_grouping.post_reserved_words(from_parameter="bob", accept_parameter="yes") + def test_subscription_in_credentials(azure_client): # valid_api_version = '2.0' azure_client.subscription_in_credentials.post_method_global_not_provided_valid() @@ -129,6 +144,7 @@ def test_subscription_in_credentials(azure_client): azure_client.subscription_in_credentials.post_path_global_valid() azure_client.subscription_in_credentials.post_swagger_global_valid() + def test_subscription_in_method(azure_client, valid_subscription): azure_client.subscription_in_method.post_method_local_valid(valid_subscription) azure_client.subscription_in_method.post_path_local_valid(valid_subscription) @@ -136,18 +152,21 @@ def test_subscription_in_method(azure_client, valid_subscription): with pytest.raises(ValueError): azure_client.subscription_in_method.post_method_local_null(None) + def test_api_version_default(azure_client): azure_client.api_version_default.get_method_global_not_provided_valid() azure_client.api_version_default.get_method_global_valid() azure_client.api_version_default.get_path_global_valid() azure_client.api_version_default.get_swagger_global_valid() + def test_api_version_local(azure_client): azure_client.api_version_local.get_method_local_valid() azure_client.api_version_local.get_method_local_null() azure_client.api_version_local.get_path_local_valid() azure_client.api_version_local.get_swagger_local_valid() + def test_skip_url_encoding(azure_client, unencoded_path, unencoded_query): azure_client.skip_url_encoding.get_method_path_valid(unencoded_path) azure_client.skip_url_encoding.get_path_valid(unencoded_path) @@ -158,8 +177,10 @@ def test_skip_url_encoding(azure_client, unencoded_path, unencoded_query): azure_client.skip_url_encoding.get_method_query_null() azure_client.skip_url_encoding.get_method_query_null(q1=None) + def test_azure_odata(azure_client): azure_client.odata.get_with_filter(filter="id gt 5 and name eq 'foo'", top=10, orderby="id") + def test_group_with_constant(client): client.parameter_grouping.group_with_constant(grouped_constant="foo", grouped_parameter="bar") diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_tracing.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_tracing.py index 7f52f25ee3b..019ee2436d6 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_tracing.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_tracing.py @@ -46,6 +46,7 @@ def test_lro(): assert not has_tracing_decorator(client.lros._put201_creating_succeeded200_initial) assert has_tracing_decorator(client.lros.begin_put201_creating_succeeded200) + def test_azure_url(): client = MicrosoftAzureTestUrl("cred", "sub_id", endpoint="dummy url") assert has_tracing_decorator(client.group.get_sample_resource_group) diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_xms.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_xms.py index 1f3ede9bf37..8fc4bd29117 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_xms.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_xms.py @@ -52,23 +52,31 @@ def client_no_request_id(credential, authentication_policy): ) as client: yield client + def test_client_request_id_in_exception(client): with pytest.raises(HttpResponseError): client.xms_client_request_id.get() + def test_xms_request_client_id_in_client_none(client): client.xms_client_request_id.get(request_id=None) + def test_xms_request_client_id_in_client(client): client.xms_client_request_id.get(request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + def test_xms_request_client_overwrite_via_parameter(client_no_request_id): # We DON'T support a Swagger parameter for request_id, the request_id policy will overwrite it. # We disable the request_id policy for this test - client_no_request_id.xms_client_request_id.param_get(headers={"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"}) + client_no_request_id.xms_client_request_id.param_get( + headers={"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} + ) + def test_xms_custom_named_request_id(client): client.header.custom_named_request_id(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") + def test_xms_custom_named_request_id_parameter_group(client): client.header.custom_named_request_id_param_grouping(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") diff --git a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_zzz.py b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_zzz.py index f50668f381c..6765911fcfa 100644 --- a/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_zzz.py +++ b/packages/autorest.python/test/azure/version-tolerant/AcceptanceTests/test_zzz.py @@ -36,8 +36,7 @@ def test_ensure_coverage(self): report = client.get_report(qualifier=platform.python_version()) # Add tests that wont be supported due to the nature of Python here - not_supported = { - } + not_supported = {} # Please add missing features or failing tests here missing_features_or_bugs = {} @@ -45,7 +44,6 @@ def test_ensure_coverage(self): print("Coverage:") self._print_report(report, not_supported, missing_features_or_bugs) - def _print_report(self, report, not_supported=None, missing_features_or_bugs=None): if not_supported: report.update(not_supported) @@ -62,6 +60,6 @@ def _print_report(self, report, not_supported=None, missing_features_or_bugs=Non print("FAILED TO EXECUTE {0}".format(s)) total_tests = len(report) - warnings.warn ("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) + warnings.warn("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) - #assert 0 == len(failed) + # assert 0 == len(failed) diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_customizations_async.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_customizations_async.py index 452153dac3a..4e778b36a29 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_customizations_async.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_customizations_async.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -30,6 +29,7 @@ from dpgcustomizationcustomizedversiontolerant.aio import DPGClient as DPGClientCustomized from dpgcustomizationcustomizedversiontolerant.models import * + @pytest.fixture async def client(client_cls): async with client_cls() as client: @@ -38,30 +38,36 @@ async def client(client_cls): CLIENTS = [DPGClientInitial, DPGClientCustomized] + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", CLIENTS) async def test_get_raw_model(client): assert await client.get_model(mode="raw") == {"received": "raw"} + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) async def test_get_customized_model(client): assert (await client.get_model("model")).received == "model" + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", CLIENTS) async def test_post_raw_model(client): assert (await client.post_model("raw", {"hello": "world!"}))["received"] == "raw" + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) async def test_post_customized_model(client): assert (await client.post_model("model", Input(hello="world!"))).received == "model" + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", CLIENTS) async def test_get_raw_pages(client): - assert [p async for p in client.get_pages("raw")] == [{'received': 'raw'}, {'received': 'raw'}] + assert [p async for p in client.get_pages("raw")] == [{"received": "raw"}, {"received": "raw"}] + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) @@ -70,11 +76,13 @@ async def test_get_customized_pages(client): assert all(p for p in pages if isinstance(p, Product)) assert all(p for p in pages if p.received == "model") + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", CLIENTS) async def test_raw_lro(client): poller = await client.begin_lro(mode="raw") - assert await poller.result() == {'provisioningState': 'Succeeded', 'received': 'raw'} + assert await poller.result() == {"provisioningState": "Succeeded", "received": "raw"} + @pytest.mark.asyncio @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) @@ -85,7 +93,10 @@ async def test_customized_lro(client): assert product.received == "model" assert product.provisioning_state == "Succeeded" -@pytest.mark.parametrize("package_name", ["dpgcustomizationinitialversiontolerant", "dpgcustomizationcustomizedversiontolerant"]) + +@pytest.mark.parametrize( + "package_name", ["dpgcustomizationinitialversiontolerant", "dpgcustomizationcustomizedversiontolerant"] +) def test_dunder_all(package_name): assert importlib.import_module(f"{package_name}.aio").__all__ == ["DPGClient"] assert importlib.import_module(f"{package_name}.aio._operations").__all__ == ["DPGClientOperationsMixin"] diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_msrest_models_async.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_msrest_models_async.py index 9d66ca83c2b..29e06b53d3f 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_msrest_models_async.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_msrest_models_async.py @@ -26,11 +26,13 @@ import pytest from dpgtestmodelsversiontolerant import aio, models + @pytest.fixture async def client(): async with aio.DPGClient() as client: yield client + @pytest.mark.asyncio async def test_paging(client): with pytest.raises(AttributeError): diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_service_driven_async.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_service_driven_async.py index 4982b2313e1..92aab71ac92 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_service_driven_async.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/asynctests/test_service_driven_async.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -29,88 +28,78 @@ from dpgservicedriveninitialversiontolerant.aio import DPGClient as DPGClientInitial from dpgservicedrivenupdateoneversiontolerant.aio import DPGClient as DPGClientUpdateOne + @pytest.fixture async def initial_client(): async with DPGClientInitial() as client: yield client + @pytest.fixture async def update_one_client(): async with DPGClientUpdateOne() as client: yield client + @pytest.mark.asyncio async def test_add_optional_parameter_to_required(initial_client, update_one_client): - await initial_client.params.get_required( - parameter="foo" - ) + await initial_client.params.get_required(parameter="foo") await update_one_client.params.get_required( parameter="foo", new_parameter="bar", ) + @pytest.mark.asyncio async def test_add_optional_parameter_to_none(initial_client, update_one_client): await initial_client.params.head_no_params() await update_one_client.params.head_no_params() - await update_one_client.params.head_no_params( - new_parameter="bar" - ) - + await update_one_client.params.head_no_params(new_parameter="bar") + + @pytest.mark.asyncio async def test_add_optional_parameter_to_required_optional(initial_client, update_one_client): - await initial_client.params.put_required_optional( - required_param="foo", - optional_param="bar" - ) - await update_one_client.params.put_required_optional( - required_param="foo", - optional_param="bar" - ) + await initial_client.params.put_required_optional(required_param="foo", optional_param="bar") + await update_one_client.params.put_required_optional(required_param="foo", optional_param="bar") await update_one_client.params.put_required_optional( - required_param="foo", - optional_param="bar", - new_parameter="baz" - ) - await update_one_client.params.put_required_optional( - required_param="foo", - new_parameter="baz" + required_param="foo", optional_param="bar", new_parameter="baz" ) + await update_one_client.params.put_required_optional(required_param="foo", new_parameter="baz") + @pytest.mark.asyncio async def test_add_optional_parameter_to_optional(initial_client, update_one_client): - await initial_client.params.get_optional( - optional_param="foo" - ) - await update_one_client.params.get_optional( - optional_param="foo" - ) - await update_one_client.params.get_optional( - optional_param="foo", - new_parameter="bar" - ) + await initial_client.params.get_optional(optional_param="foo") + await update_one_client.params.get_optional(optional_param="foo") + await update_one_client.params.get_optional(optional_param="foo", new_parameter="bar") + @pytest.mark.asyncio async def test_add_new_content_type(initial_client, update_one_client): - await initial_client.params.post_parameters({ "url": "http://example.org/myimage.jpeg" }) - await update_one_client.params.post_parameters({ "url": "http://example.org/myimage.jpeg" }) + await initial_client.params.post_parameters({"url": "http://example.org/myimage.jpeg"}) + await update_one_client.params.post_parameters({"url": "http://example.org/myimage.jpeg"}) await update_one_client.params.post_parameters(b"hello", content_type="image/jpeg") + @pytest.mark.asyncio async def test_add_new_operation(initial_client, update_one_client): with pytest.raises(AttributeError): await initial_client.params.delete_parameters() await update_one_client.params.delete_parameters() + @pytest.mark.asyncio async def test_add_new_path(initial_client, update_one_client): with pytest.raises(AttributeError): await initial_client.params.get_new_operation() - assert await update_one_client.params.get_new_operation() == {'message': 'An object was successfully returned'} + assert await update_one_client.params.get_new_operation() == {"message": "An object was successfully returned"} + @pytest.mark.asyncio async def test_glass_breaker(update_one_client): - request = HttpRequest(method="GET", url="/servicedriven/glassbreaker", params=[], headers={"Accept": "application/json"}) + request = HttpRequest( + method="GET", url="/servicedriven/glassbreaker", params=[], headers={"Accept": "application/json"} + ) response = await update_one_client.send_request(request) assert response.status_code == 200 - assert response.json() == {'message': 'An object was successfully returned'} + assert response.json() == {"message": "An object was successfully returned"} diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/conftest.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/conftest.py index 38d120a44f3..a7618f840ae 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/conftest.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/conftest.py @@ -29,23 +29,29 @@ import os import signal from os.path import dirname, realpath + cwd = dirname(realpath(__file__)) -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def start_server_process(): - cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format(cwd) - if os.name == 'nt': #On windows, subprocess creation works without being in the shell + cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format( + cwd + ) + if os.name == "nt": # On windows, subprocess creation works without being in the shell return subprocess.Popen(cmd) - return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) #On linux, have to set shell=True + return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # On linux, have to set shell=True -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session") def testserver(): """Start the Autorest testserver.""" diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_customizations.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_customizations.py index 6d42afd005d..92bcd10ce4d 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_customizations.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_customizations.py @@ -32,32 +32,40 @@ from dpgcustomizationcustomizedversiontolerant import DPGClient as DPGClientCustomized from dpgcustomizationcustomizedversiontolerant.models import * + @pytest.fixture def client(client_cls): with client_cls() as client: yield client + CLIENTS = [DPGClientInitial, DPGClientCustomized] + @pytest.mark.parametrize("client_cls", CLIENTS) def test_get_raw_model(client): assert client.get_model(mode="raw") == {"received": "raw"} + @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) def test_get_customized_model(client): assert client.get_model("model").received == "model" + @pytest.mark.parametrize("client_cls", CLIENTS) def test_post_raw_model(client): assert client.post_model("raw", {"hello": "world!"})["received"] == "raw" + @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) def test_post_customized_model(client): assert client.post_model("model", Input(hello="world!")).received == "model" + @pytest.mark.parametrize("client_cls", CLIENTS) def test_get_raw_pages(client): - assert list(client.get_pages("raw")) == [{'received': 'raw'}, {'received': 'raw'}] + assert list(client.get_pages("raw")) == [{"received": "raw"}, {"received": "raw"}] + @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) def test_get_customized_pages(client): @@ -65,9 +73,11 @@ def test_get_customized_pages(client): assert all(p for p in pages if isinstance(p, Product)) assert all(p for p in pages if p.received == "model") + @pytest.mark.parametrize("client_cls", CLIENTS) def test_raw_lro(client): - assert client.begin_lro(mode="raw").result() == {'provisioningState': 'Succeeded', 'received': 'raw'} + assert client.begin_lro(mode="raw").result() == {"provisioningState": "Succeeded", "received": "raw"} + @pytest.mark.parametrize("client_cls", [DPGClientCustomized]) def test_customized_lro(client): @@ -76,21 +86,24 @@ def test_customized_lro(client): assert product.received == "model" assert product.provisioning_state == "Succeeded" -@pytest.mark.parametrize("package_name", ["dpgcustomizationinitialversiontolerant", "dpgcustomizationcustomizedversiontolerant"]) + +@pytest.mark.parametrize( + "package_name", ["dpgcustomizationinitialversiontolerant", "dpgcustomizationcustomizedversiontolerant"] +) def test_dunder_all(package_name): assert importlib.import_module(package_name).__all__ == ["DPGClient"] assert importlib.import_module(f"{package_name}._operations").__all__ == ["DPGClientOperationsMixin"] + def test_imports(): # make sure we can import all of the models we've added to the customization class - from dpgcustomizationcustomizedversiontolerant.models import ( - Input, LROProduct, Product - ) + from dpgcustomizationcustomizedversiontolerant.models import Input, LROProduct, Product + models = [Input, LROProduct, Product] # check public models public_models = [ - name for name, obj in - inspect.getmembers(sys.modules["dpgcustomizationcustomizedversiontolerant.models"]) + name + for name, obj in inspect.getmembers(sys.modules["dpgcustomizationcustomizedversiontolerant.models"]) if name[0] != "_" and obj in models ] assert len(public_models) == 3 diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_msrest_models.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_msrest_models.py index b9e4c82a96f..53607da953f 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_msrest_models.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_msrest_models.py @@ -26,11 +26,13 @@ import pytest from dpgtestmodelsversiontolerant import DPGClient, models + @pytest.fixture def client(): with DPGClient() as client: yield client + def test_paging(client: DPGClient): with pytest.raises(AttributeError): models.ProductResult diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_postprocess_plugin.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_postprocess_plugin.py index 7c8b9792119..338f4754a1b 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_postprocess_plugin.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_postprocess_plugin.py @@ -25,10 +25,12 @@ # -------------------------------------------------------------------------- from dpgtestmodelsversiontolerant import models + def test_added_property(): product = models.Product(received="model") assert product.added_in_customization == "bonjour!" + def test_added_model(): added_model = models.AddedModel() assert added_model.added_model_property == "Added!" diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_service_driven.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_service_driven.py index 10ad0c08ab4..96731da8c22 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_service_driven.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_service_driven.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -29,83 +28,69 @@ from dpgservicedriveninitialversiontolerant import DPGClient as DPGClientInitial from dpgservicedrivenupdateoneversiontolerant import DPGClient as DPGClientUpdateOne + @pytest.fixture def initial_client(): with DPGClientInitial() as client: yield client + @pytest.fixture def update_one_client(): with DPGClientUpdateOne() as client: yield client + def test_add_optional_parameter_to_required(initial_client, update_one_client): - initial_client.params.get_required( - parameter="foo" - ) - update_one_client.params.get_required( - parameter="foo" - ) + initial_client.params.get_required(parameter="foo") + update_one_client.params.get_required(parameter="foo") update_one_client.params.get_required( parameter="foo", new_parameter="bar", ) + def test_add_optional_parameter_to_none(initial_client, update_one_client): initial_client.params.head_no_params() update_one_client.params.head_no_params() - update_one_client.params.head_no_params( - new_parameter="bar" - ) + update_one_client.params.head_no_params(new_parameter="bar") + def test_add_optional_parameter_to_required_optional(initial_client, update_one_client): - initial_client.params.put_required_optional( - required_param="foo", - optional_param="bar" - ) - update_one_client.params.put_required_optional( - required_param="foo", - optional_param="bar" - ) - update_one_client.params.put_required_optional( - required_param="foo", - optional_param="bar", - new_parameter="baz" - ) - update_one_client.params.put_required_optional( - required_param="foo", - new_parameter="baz" - ) + initial_client.params.put_required_optional(required_param="foo", optional_param="bar") + update_one_client.params.put_required_optional(required_param="foo", optional_param="bar") + update_one_client.params.put_required_optional(required_param="foo", optional_param="bar", new_parameter="baz") + update_one_client.params.put_required_optional(required_param="foo", new_parameter="baz") + def test_add_optional_parameter_to_optional(initial_client, update_one_client): - initial_client.params.get_optional( - optional_param="foo" - ) - update_one_client.params.get_optional( - optional_param="foo" - ) - update_one_client.params.get_optional( - optional_param="foo", - new_parameter="bar" - ) + initial_client.params.get_optional(optional_param="foo") + update_one_client.params.get_optional(optional_param="foo") + update_one_client.params.get_optional(optional_param="foo", new_parameter="bar") + def test_add_new_content_type(initial_client, update_one_client): - initial_client.params.post_parameters({ "url": "http://example.org/myimage.jpeg" }) - update_one_client.params.post_parameters({ "url": "http://example.org/myimage.jpeg" }) + initial_client.params.post_parameters({"url": "http://example.org/myimage.jpeg"}) + update_one_client.params.post_parameters({"url": "http://example.org/myimage.jpeg"}) update_one_client.params.post_parameters(b"hello", content_type="image/jpeg") + def test_add_new_operation(initial_client, update_one_client): with pytest.raises(AttributeError): initial_client.params.delete_parameters() update_one_client.params.delete_parameters() + def test_add_new_path(initial_client, update_one_client): with pytest.raises(AttributeError): initial_client.params.get_new_operation() - assert update_one_client.params.get_new_operation() == {'message': 'An object was successfully returned'} + assert update_one_client.params.get_new_operation() == {"message": "An object was successfully returned"} + def test_glass_breaker(update_one_client): - request = HttpRequest(method="GET", url="/servicedriven/glassbreaker", params=[], headers={"Accept": "application/json"}) + request = HttpRequest( + method="GET", url="/servicedriven/glassbreaker", params=[], headers={"Accept": "application/json"} + ) response = update_one_client.send_request(request) assert response.status_code == 200 - assert response.json() == {'message': 'An object was successfully returned'} + assert response.json() == {"message": "An object was successfully returned"} diff --git a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_zzz.py b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_zzz.py index 8f9e9c1ca15..4cf57e66a26 100644 --- a/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_zzz.py +++ b/packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_zzz.py @@ -34,17 +34,17 @@ class TestAcceptance(object): def test_ensure_coverage(self): client = DPGClient() - request = HttpRequest("GET", "http://localhost:3000/report/dpg", params={"qualifier": platform.python_version()}) + request = HttpRequest( + "GET", "http://localhost:3000/report/dpg", params={"qualifier": platform.python_version()} + ) response = client.send_request(request) response.raise_for_status() support_dict = response.json() # Add tests that wont be supported due to the nature of Python here - not_supported = { - } + not_supported = {} # Please add missing features or failing tests here - missing_features_or_bugs = { - } + missing_features_or_bugs = {} for name in support_dict: if "DPG" not in name: # this folder only does dpg @@ -69,6 +69,6 @@ def _print_report(self, report, not_supported=None, missing_features_or_bugs=Non print("FAILED TO EXECUTE {0}".format(s)) total_tests = len(report) - warnings.warn ("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) + warnings.warn("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) assert 0 == len(failed) diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/multiapi_base.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/multiapi_base.py index adc63612f88..3426c5c257c 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/multiapi_base.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/multiapi_base.py @@ -33,14 +33,17 @@ def default_client(): pass + @pytest.fixture def client(): pass + @pytest.fixture def namespace_models(): pass + class NotTested(object): class TestMultiapiBase(object): @@ -84,7 +87,7 @@ async def test_default_models_from_operation_group(self, default_client): with pytest.raises(AttributeError): models.ModelTwo(id=1) - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_specify_models_from_operation_group(self, client): v1_models = client.operation_group_one.models @@ -102,13 +105,13 @@ async def test_default_operation_mixin(self, default_client, namespace_models): response = await default_client.test_one(id=1, message=None) assert response == namespace_models.ModelTwo(id=1, message="This was called with api-version 2.0.0") - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_specificy_api_version_operation_mixin(self, client): response = await client.test_one(id=1, message="This is from api version One") assert response is None - @pytest.mark.parametrize('api_version', ["3.0.0"]) + @pytest.mark.parametrize("api_version", ["3.0.0"]) @pytest.mark.asyncio async def test_specify_api_version_with_no_mixin(self, client): with pytest.raises(ValueError): @@ -123,7 +126,7 @@ async def test_default_operation_group_one(self, default_client, namespace_model with pytest.raises(AttributeError): response = await client.operation_group_one.test_three() - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_version_one_operation_group_one(self, client): response = await client.operation_group_one.test_two() @@ -132,7 +135,7 @@ async def test_version_one_operation_group_one(self, client): with pytest.raises(AttributeError): response = await client.operation_group_one.test_three() - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) @pytest.mark.asyncio async def test_version_two_operation_group_one(self, client, namespace_models): parameter = client.operation_group_one.models.ModelTwo( @@ -153,9 +156,7 @@ async def test_default_operation_group_two_test_four_json(self, default_client): @pytest.mark.asyncio async def test_default_operation_group_two_test_four_pdf(self, default_client): - response = await default_client.operation_group_two.test_four( - input=b"PDF", content_type="application/pdf" - ) + response = await default_client.operation_group_two.test_four(input=b"PDF", content_type="application/pdf") assert response is None @pytest.mark.asyncio @@ -163,13 +164,13 @@ async def test_default_operation_group_two_test_five(self, default_client): response = await default_client.operation_group_two.test_five() assert response is None - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_version_one_operation_group_two_error(self, client): with pytest.raises(AttributeError): await client.operation_group_one.test_four() - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) @pytest.mark.asyncio async def test_version_two_operation_group_two(self, client): response = await client.operation_group_two.test_four(parameter_one=True) @@ -178,7 +179,7 @@ async def test_version_two_operation_group_two(self, client): with pytest.raises(AttributeError): response = await client.operation_group_two.test_five() - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_lro(self, client, namespace_models): poller = await client.begin_test_lro(namespace_models.Product()) @@ -203,7 +204,7 @@ async def test_operation_group_paging(self, default_client, namespace_models): assert isinstance(items[0], namespace_models.ModelThree) assert items[0].optional_property == "paged" - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_lro_and_paging(self, client, namespace_models): poller = await client.begin_test_lro_and_paging() diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi.py index 5047559ca6d..9a60e0d01f1 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi.py @@ -37,76 +37,93 @@ @async_generator async def default_client(credential, authentication_policy): from multiapi.aio import MultiapiServiceClient + async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: await yield_(default_client) + @pytest.fixture @async_generator async def client(credential, authentication_policy, api_version): from multiapi.aio import MultiapiServiceClient async with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: await yield_(client) + @pytest.fixture def namespace_models(): from multiapi import models + return models -@pytest.mark.parametrize('api_version', ["2.0.0"]) + +@pytest.mark.parametrize("api_version", ["2.0.0"]) def test_specify_api_version_multiapi_client(client): assert client.profile.label == "multiapi.MultiapiServiceClient 2.0.0" + def test_configuration_kwargs(default_client): # making sure that the package name is correct in the sdk moniker assert default_client._config.user_agent_policy._user_agent.startswith("azsdk-python-multiapi/") + def test_pipeline_client(default_client): # assert the pipeline client is AsyncARMPipelineClient from azure.mgmt.core, since this is mgmt plane assert type(default_client._client) == AsyncARMPipelineClient + def test_arm_http_logging_policy_default(default_client): assert isinstance(default_client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + default_client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) + @pytest.mark.asyncio async def test_arm_http_logging_policy_custom(credential): from multiapi.aio import MultiapiServiceClient + http_logging_policy = ARMHttpLoggingPolicy(base_url="test") http_logging_policy = ARMHttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - http_logging_policy=http_logging_policy + base_url="http://localhost:3000", credential=credential, http_logging_policy=http_logging_policy ) as default_client: assert isinstance(default_client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + default_client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) + @pytest.mark.asyncio async def test_credential_scopes_default(credential): from multiapi.aio import MultiapiServiceClient + async with MultiapiServiceClient(credential=credential) as client: - assert client._config.credential_scopes == ['https://management.azure.com/.default'] + assert client._config.credential_scopes == ["https://management.azure.com/.default"] + @pytest.mark.asyncio async def test_credential_scopes_override(credential): from multiapi.aio import MultiapiServiceClient - async with MultiapiServiceClient(credential=credential, credential_scopes=["http://i-should-be-the-only-credential"]) as client: + + async with MultiapiServiceClient( + credential=credential, credential_scopes=["http://i-should-be-the-only-credential"] + ) as client: assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] -@pytest.mark.parametrize('api_version', ["0.0.0"]) + +@pytest.mark.parametrize("api_version", ["0.0.0"]) @pytest.mark.asyncio async def test_only_operation_groups(client): assert client.operation_group_one.test_two # this is the only function it has access to. diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_combiner.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_combiner.py index 0e05460b769..de3774f0000 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_combiner.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_combiner.py @@ -32,31 +32,34 @@ @async_generator async def default_client(credential, authentication_policy): from multiapicombiner.aio import MultiapiServiceClient + async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: await yield_(default_client) + @pytest.fixture @async_generator async def client(credential, authentication_policy, api_version): from multiapi.aio import MultiapiServiceClient async with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: await yield_(client) + @pytest.fixture def namespace_models(): from multiapicombiner import models + return models + class TestMultiapiCombinerClient(NotTested.TestMultiapiBase): @pytest.mark.asyncio async def test_default_models(self, default_client): @@ -70,12 +73,12 @@ async def test_specify_api_version_models(self, default_client): async def test_default_models_from_operation_group(self, default_client): pass - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_lro_and_paging(self, client, namespace_models): pass - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) @pytest.mark.asyncio async def test_version_two_operation_group_one(self, client, namespace_models): pass diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_credential_default_policy.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_credential_default_policy.py index a1a03809726..095ef255b8e 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_credential_default_policy.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_credential_default_policy.py @@ -28,16 +28,18 @@ from azure.core.pipeline.policies import AzureKeyCredentialPolicy from azure.core.credentials import AzureKeyCredential + @pytest.fixture @async_generator async def default_client(credential, authentication_policy): from multiapicredentialdefaultpolicy.aio import MultiapiServiceClient + async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=AzureKeyCredential("12345") + base_url="http://localhost:3000", credential=AzureKeyCredential("12345") ) as default_client: await yield_(default_client) + def test_multiapi_credential_default_policy_type(default_client): # making sure that the authentication policy is AzureKeyCredentialPolicy assert isinstance(default_client._config.authentication_policy, AzureKeyCredentialPolicy) diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_custom_base_url.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_custom_base_url.py index 130de363aff..6de82ae9822 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_custom_base_url.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_custom_base_url.py @@ -27,26 +27,28 @@ from async_generator import yield_, async_generator from multiapicustombaseurl.aio import MultiapiCustomBaseUrlServiceClient + @pytest.fixture @async_generator async def client(credential, authentication_policy, api_version): async with MultiapiCustomBaseUrlServiceClient( - endpoint="http://localhost:3000", + endpoint="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: await yield_(client) + class TestMultiapiCustomBaseUrl(object): - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) @pytest.mark.asyncio async def test_custom_base_url_version_one(self, client): await client.test(id=1) - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) @pytest.mark.asyncio async def test_custom_base_url_version_two(self, client): await client.test(id=2) diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_data_plane.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_data_plane.py index 2f7a2b93e39..885f60abc13 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_data_plane.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_data_plane.py @@ -37,62 +37,72 @@ @async_generator async def default_client(credential, authentication_policy): from multiapidataplane.aio import MultiapiServiceClient + async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: await yield_(default_client) + @pytest.fixture @async_generator async def client(credential, authentication_policy, api_version): from multiapidataplane.aio import MultiapiServiceClient async with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: await yield_(client) + @pytest.fixture def namespace_models(): from multiapidataplane import models + return models -@pytest.mark.parametrize('api_version', ["2.0.0"]) + +@pytest.mark.parametrize("api_version", ["2.0.0"]) def test_specify_api_version_multiapi_client(client): assert client.profile.label == "multiapidataplane.MultiapiServiceClient 2.0.0" + def test_configuration_kwargs(default_client): # making sure that the package name is correct in the sdk moniker assert default_client._config.user_agent_policy._user_agent.startswith("azsdk-python-multiapidataplane/") + def test_pipeline_client(default_client): # assert the pipeline client is AsyncPipelineClient from azure.core, since this is data plane assert type(default_client._client) == AsyncPipelineClient + def test_arm_http_logging_policy_default(default_client): assert isinstance(default_client._config.http_logging_policy, HttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + default_client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) + @pytest.mark.asyncio async def test_arm_http_logging_policy_custom(credential): from multiapi.aio import MultiapiServiceClient + http_logging_policy = HttpLoggingPolicy(base_url="test") http_logging_policy = HttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - http_logging_policy=http_logging_policy + base_url="http://localhost:3000", credential=credential, http_logging_policy=http_logging_policy ) as default_client: assert isinstance(default_client._config.http_logging_policy, HttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + default_client._config.http_logging_policy.allowed_header_names + == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) + class TestMultiapiClient(NotTested.TestMultiapiBase): pass diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_keyword_only.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_keyword_only.py index 79c61c70c3a..991bea06477 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_keyword_only.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_keyword_only.py @@ -28,31 +28,34 @@ from multiapikeywordonly.aio import MultiapiServiceClient from .multiapi_base import NotTested + @pytest.fixture @async_generator async def client(credential, authentication_policy, api_version): async with MultiapiServiceClient( - endpoint="http://localhost:3000", + endpoint="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: await yield_(client) + @pytest.fixture @async_generator async def default_client(credential, authentication_policy): async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: await yield_(default_client) + @pytest.fixture def namespace_models(): from multiapikeywordonly import models + return models + class TestMultiapiClientKeywordOnly(NotTested.TestMultiapiBase): pass diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_security.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_security.py index 6231066eca9..7a8a99f313e 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_security.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_security.py @@ -27,6 +27,7 @@ from multiapisecurity.aio import MultiapiServiceClient from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy + @pytest.mark.asyncio async def test_multiapi_security(credential): async with MultiapiServiceClient(credential=credential) as client: diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_submodule.py b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_submodule.py index 9244103e85a..166225f9490 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_submodule.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/asynctests/test_multiapi_submodule.py @@ -36,38 +36,43 @@ @async_generator async def default_client(credential, authentication_policy): from multiapiwithsubmodule.submodule.aio import MultiapiServiceClient + async with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: await yield_(default_client) + @pytest.fixture @async_generator async def client(credential, authentication_policy, api_version): from multiapiwithsubmodule.submodule.aio import MultiapiServiceClient + async with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: await yield_(client) + @pytest.fixture def namespace_models(): from multiapiwithsubmodule.submodule import models + return models -@pytest.mark.parametrize('api_version', ["2.0.0"]) +@pytest.mark.parametrize("api_version", ["2.0.0"]) def test_specify_api_version_multiapi_client(client): assert client.profile.label == "multiapiwithsubmodule.submodule.MultiapiServiceClient 2.0.0" + def test_configuration_kwargs(default_client): # making sure that the package name is correct in the sdk moniker assert default_client._config.user_agent_policy._user_agent.startswith("azsdk-python-multiapiwithsubmodule/") + class TestMultiapiSubmodule(NotTested.TestMultiapiBase): - pass \ No newline at end of file + pass diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/conftest.py b/packages/autorest.python/test/multiapi/AcceptanceTests/conftest.py index 3f0aea15589..39147045ced 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/conftest.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/conftest.py @@ -33,21 +33,26 @@ cwd = os.path.dirname(os.path.realpath(__file__)) -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def start_server_process(): - cmd = "node {}/../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format(cwd) - if os.name == 'nt': #On windows, subprocess creation works without being in the shell + cmd = "node {}/../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format( + cwd + ) + if os.name == "nt": # On windows, subprocess creation works without being in the shell return subprocess.Popen(cmd) - return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) #On linux, have to set shell=True + return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # On linux, have to set shell=True + -#Ideally this would be in a common helper library shared between the tests +# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session") def testserver(): """Start the Autorest testserver.""" @@ -55,12 +60,15 @@ def testserver(): yield terminate_server_process(server) + @pytest.fixture def credential(): class FakeCredential: pass + return FakeCredential() + @pytest.fixture def authentication_policy(): - return SansIOHTTPPolicy() \ No newline at end of file + return SansIOHTTPPolicy() diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/multiapi_base.py b/packages/autorest.python/test/multiapi/AcceptanceTests/multiapi_base.py index 75e8016a82a..cd597e83662 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/multiapi_base.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/multiapi_base.py @@ -28,18 +28,22 @@ import json from azure.profiles import KnownProfiles + @pytest.fixture def default_client(): pass + @pytest.fixture def client(): pass + @pytest.fixture def namespace_models(): pass + class NotTested(object): class TestMultiapiBase(object): @@ -79,7 +83,7 @@ def test_default_models_from_operation_group(self, default_client): with pytest.raises(AttributeError): models.ModelTwo(id=1) - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_specify_models_from_operation_group(self, client): v1_models = client.operation_group_one.models @@ -95,12 +99,12 @@ def test_default_operation_mixin(self, default_client, namespace_models): response = default_client.test_one(id=1, message=None) assert response == namespace_models.ModelTwo(id=1, message="This was called with api-version 2.0.0") - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_specificy_api_version_operation_mixin(self, client): response = client.test_one(id=1, message="This is from api version One") assert response is None - @pytest.mark.parametrize('api_version', ["3.0.0"]) + @pytest.mark.parametrize("api_version", ["3.0.0"]) def test_specify_api_version_with_no_mixin(self, client): with pytest.raises(ValueError): client.test_one(id=1, message="This should throw") @@ -113,7 +117,7 @@ def test_default_operation_group_one(self, default_client, namespace_models): with pytest.raises(AttributeError): response = client.operation_group_one.test_three() - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_version_one_operation_group_one(self, client): response = client.operation_group_one.test_two() assert response is None @@ -121,7 +125,7 @@ def test_version_one_operation_group_one(self, client): with pytest.raises(AttributeError): response = client.operation_group_one.test_three() - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) def test_version_two_operation_group_one(self, client, namespace_models): parameter = client.operation_group_one.models.ModelTwo( id=1, message="This should be sent from api version 2.0.0" @@ -139,21 +143,19 @@ def test_default_operation_group_two_test_four_json(self, default_client): assert response is None def test_default_operation_group_two_test_four_pdf(self, default_client): - response = default_client.operation_group_two.test_four( - input=b"PDF", content_type="application/pdf" - ) + response = default_client.operation_group_two.test_four(input=b"PDF", content_type="application/pdf") assert response is None def test_default_operation_group_two_test_five(self, default_client): response = default_client.operation_group_two.test_five() assert response is None - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_version_one_operation_group_two_error(self, client): with pytest.raises(AttributeError): client.operation_group_one.test_four() - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) def test_version_two_operation_group_two(self, client): response = client.operation_group_two.test_four(parameter_one=True) assert response is None @@ -161,7 +163,7 @@ def test_version_two_operation_group_two(self, client): with pytest.raises(AttributeError): response = client.operation_group_two.test_five() - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_lro(self, client, namespace_models): product = client.begin_test_lro(namespace_models.Product()).result() assert product.id == 100 @@ -180,7 +182,7 @@ def test_operation_group_paging(self, default_client, namespace_models): assert isinstance(items[0], namespace_models.ModelThree) assert items[0].optional_property == "paged" - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_lro_and_paging(self, client, namespace_models): poller = client.begin_test_lro_and_paging() pager = poller.result() diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi.py index 4bd880a61fd..20ab21431d6 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi.py @@ -35,76 +35,93 @@ @pytest.fixture def default_client(credential, authentication_policy): from multiapi import MultiapiServiceClient + with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: yield default_client + @pytest.fixture def client(credential, authentication_policy, api_version): from multiapi import MultiapiServiceClient with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: yield client + @pytest.fixture def namespace_models(): from multiapi import models + return models -@pytest.mark.parametrize('api_version', ["2.0.0"]) +@pytest.mark.parametrize("api_version", ["2.0.0"]) def test_specify_api_version_multiapi_client(client): assert client.profile.label == "multiapi.MultiapiServiceClient 2.0.0" + def test_configuration_kwargs(default_client): # making sure that the package name is correct in the sdk moniker assert default_client._config.user_agent_policy._user_agent.startswith("azsdk-python-multiapi/") + def test_patch_file(): from multiapi.models import PatchAddedModel + def test_pipeline_client(default_client): # assert the pipeline client is ARMPipelineClient from azure.mgmt.core, since this is mgmt plane assert type(default_client._client) == ARMPipelineClient + def test_arm_http_logging_policy_default(default_client): assert isinstance(default_client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + default_client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) + def test_arm_http_logging_policy_custom(credential): from multiapi import MultiapiServiceClient + http_logging_policy = ARMHttpLoggingPolicy(base_url="test") http_logging_policy = ARMHttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - http_logging_policy=http_logging_policy + base_url="http://localhost:3000", credential=credential, http_logging_policy=http_logging_policy ) as default_client: assert isinstance(default_client._config.http_logging_policy, ARMHttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + default_client._config.http_logging_policy.allowed_header_names + == ARMHttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) + def test_credential_scopes_default(credential): from multiapi import MultiapiServiceClient + with MultiapiServiceClient(credential=credential) as client: - assert client._config.credential_scopes == ['https://management.azure.com/.default'] + assert client._config.credential_scopes == ["https://management.azure.com/.default"] + def test_credential_scopes_override(credential): from multiapi import MultiapiServiceClient - with MultiapiServiceClient(credential=credential, credential_scopes=["http://i-should-be-the-only-credential"]) as client: + + with MultiapiServiceClient( + credential=credential, credential_scopes=["http://i-should-be-the-only-credential"] + ) as client: assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] -@pytest.mark.parametrize('api_version', ["0.0.0"]) + +@pytest.mark.parametrize("api_version", ["0.0.0"]) def test_only_operation_groups(client): assert client.operation_group_one.test_two # this is the only function it has access to. with pytest.raises(ValueError): @@ -113,6 +130,7 @@ def test_only_operation_groups(client): # check that it doesn't have access to a mixin operation with pytest.raises(ValueError): client.test_one("1", "hello") + + class TestMultiapiClient(NotTested.TestMultiapiBase): pass - diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_combiner.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_combiner.py index 63ca6d27160..556699b8907 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_combiner.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_combiner.py @@ -31,9 +31,7 @@ @pytest.fixture def default_client(credential, authentication_policy): with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: yield default_client @@ -44,7 +42,7 @@ def client(credential, authentication_policy, api_version): base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: yield client @@ -52,6 +50,7 @@ def client(credential, authentication_policy, api_version): @pytest.fixture def namespace_models(): from multiapicombiner import models + return models @@ -65,7 +64,7 @@ def test_specify_api_version_models(self, default_client): def test_default_models_from_operation_group(self, default_client): pass - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_specify_models_from_operation_group(self, client): pass @@ -73,7 +72,7 @@ def test_default_operation_mixin(self, default_client, namespace_models): response = default_client.test_one(id=1, message=None) assert response == namespace_models.ModelTwo(id=1, message="This was called with api-version 2.0.0") - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_version_one_operation_group_one(self, client): response = client.operation_group_one.test_two() assert response is None @@ -81,14 +80,14 @@ def test_version_one_operation_group_one(self, client): with pytest.raises(ValueError): client.operation_group_one.test_three() - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) def test_version_two_operation_group_one(self, client, namespace_models): pass - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) def test_version_two_operation_group_two(self, client): pass - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_lro_and_paging(self, client, namespace_models): pass diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_credential_default_policy.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_credential_default_policy.py index 35d774b8023..8df9624e1c5 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_credential_default_policy.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_credential_default_policy.py @@ -27,15 +27,17 @@ from azure.core.pipeline.policies import AzureKeyCredentialPolicy from azure.core.credentials import AzureKeyCredential + @pytest.fixture def default_client(authentication_policy): from multiapicredentialdefaultpolicy import MultiapiServiceClient + with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=AzureKeyCredential("12345") + base_url="http://localhost:3000", credential=AzureKeyCredential("12345") ) as default_client: yield default_client + def test_multiapi_credential_default_policy_type(default_client): # making sure that the authentication policy is AzureKeyCredentialPolicy assert isinstance(default_client._config.authentication_policy, AzureKeyCredentialPolicy) diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_custom_base_url.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_custom_base_url.py index e3d6ce4d1aa..25cda644f14 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_custom_base_url.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_custom_base_url.py @@ -26,23 +26,25 @@ import pytest from multiapicustombaseurl import MultiapiCustomBaseUrlServiceClient + @pytest.fixture def client(credential, authentication_policy, api_version): with MultiapiCustomBaseUrlServiceClient( - endpoint="http://localhost:3000", + endpoint="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: yield client + class TestMultiapiCustomBaseUrl(object): - @pytest.mark.parametrize('api_version', ["1.0.0"]) + @pytest.mark.parametrize("api_version", ["1.0.0"]) def test_custom_base_url_version_one(self, client): client.test(id=1) - @pytest.mark.parametrize('api_version', ["2.0.0"]) + @pytest.mark.parametrize("api_version", ["2.0.0"]) def test_custom_base_url_version_two(self, client): client.test(id=2) diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_data_plane.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_data_plane.py index fca0981eafc..1780fa81a14 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_data_plane.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_data_plane.py @@ -35,62 +35,70 @@ @pytest.fixture def default_client(credential, authentication_policy): from multiapidataplane import MultiapiServiceClient + with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: yield default_client + @pytest.fixture def client(credential, authentication_policy, api_version): from multiapidataplane import MultiapiServiceClient with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: yield client + @pytest.fixture def namespace_models(): from multiapidataplane import models + return models -@pytest.mark.parametrize('api_version', ["2.0.0"]) +@pytest.mark.parametrize("api_version", ["2.0.0"]) def test_specify_api_version_multiapi_client(client): assert client.profile.label == "multiapidataplane.MultiapiServiceClient 2.0.0" + def test_configuration_kwargs(default_client): # making sure that the package name is correct in the sdk moniker assert default_client._config.user_agent_policy._user_agent.startswith("azsdk-python-multiapidataplane/") + def test_pipeline_client(default_client): # assert the pipeline client is PipelineClient from azure.core, since this is data plane assert type(default_client._client) == PipelineClient + def test_arm_http_logging_policy_default(default_client): assert isinstance(default_client._config.http_logging_policy, HttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + default_client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) + def test_arm_http_logging_policy_custom(credential): from multiapi import MultiapiServiceClient + http_logging_policy = HttpLoggingPolicy(base_url="test") http_logging_policy = HttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - http_logging_policy=http_logging_policy + base_url="http://localhost:3000", credential=credential, http_logging_policy=http_logging_policy ) as default_client: assert isinstance(default_client._config.http_logging_policy, HttpLoggingPolicy) - assert default_client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + default_client._config.http_logging_policy.allowed_header_names + == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) + class TestMultiapiClient(NotTested.TestMultiapiBase): pass - diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_keyword_only.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_keyword_only.py index 0cf5160a3cd..65fca79550c 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_keyword_only.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_keyword_only.py @@ -27,29 +27,32 @@ from multiapikeywordonly import MultiapiServiceClient from .multiapi_base import NotTested + @pytest.fixture def default_client(credential, authentication_policy): with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: yield default_client + @pytest.fixture def client(credential, authentication_policy, api_version): with MultiapiServiceClient( - endpoint="http://localhost:3000", + endpoint="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: yield client + @pytest.fixture def namespace_models(): from multiapikeywordonly import models + return models + class TestMultiapiClientKeywordOnly(NotTested.TestMultiapiBase): pass diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_no_async.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_no_async.py index f6a8037050c..2781b96deb7 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_no_async.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_no_async.py @@ -25,6 +25,7 @@ # -------------------------------------------------------------------------- import pytest + def test_multiapi_no_async(): # making sure that there is no aio folder with pytest.raises(ImportError): diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_security.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_security.py index 0270a058deb..3bd89514177 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_security.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_security.py @@ -26,6 +26,7 @@ from multiapisecurity import MultiapiServiceClient from azure.core.pipeline.policies import BearerTokenCredentialPolicy + def test_multiapi_security(credential): with MultiapiServiceClient(credential=credential) as client: assert isinstance(client._config.authentication_policy, BearerTokenCredentialPolicy) diff --git a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_submodule.py b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_submodule.py index cf34c658ae8..2bb1ef36f67 100644 --- a/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_submodule.py +++ b/packages/autorest.python/test/multiapi/AcceptanceTests/test_multiapi_submodule.py @@ -34,37 +34,42 @@ @pytest.fixture def default_client(credential, authentication_policy): from multiapiwithsubmodule.submodule import MultiapiServiceClient + with MultiapiServiceClient( - base_url="http://localhost:3000", - credential=credential, - authentication_policy=authentication_policy + base_url="http://localhost:3000", credential=credential, authentication_policy=authentication_policy ) as default_client: yield default_client + @pytest.fixture def client(credential, authentication_policy, api_version): from multiapiwithsubmodule.submodule import MultiapiServiceClient + with MultiapiServiceClient( - base_url="http://localhost:3000", + base_url="http://localhost:3000", api_version=api_version, credential=credential, - authentication_policy=authentication_policy + authentication_policy=authentication_policy, ) as client: yield client + @pytest.fixture def namespace_models(): from multiapiwithsubmodule.submodule import models + return models -@pytest.mark.parametrize('api_version', ["2.0.0"]) +@pytest.mark.parametrize("api_version", ["2.0.0"]) def test_specify_api_version_multiapi_client(client): assert client.profile.label == "multiapiwithsubmodule.submodule.MultiapiServiceClient 2.0.0" + def test_configuration_kwargs(default_client): # making sure that the package name is correct in the sdk moniker assert default_client._config.user_agent_policy._user_agent.startswith("azsdk-python-multiapiwithsubmodule/") + class TestMultiapiSubmodule(NotTested.TestMultiapiBase): - pass \ No newline at end of file + pass diff --git a/packages/autorest.python/test/multiapi/run_multiapi_combiner.py b/packages/autorest.python/test/multiapi/run_multiapi_combiner.py index aae27619d59..50c2622b7c9 100644 --- a/packages/autorest.python/test/multiapi/run_multiapi_combiner.py +++ b/packages/autorest.python/test/multiapi/run_multiapi_combiner.py @@ -11,6 +11,7 @@ import tempfile import venv + def main(): test_root = Path(os.getcwd()) / "test/multiapi" @@ -36,5 +37,5 @@ def main(): check_call([venv_context.env_exe, "-m", "packaging_tools.multiapi_combiner", "--pkg-path", os.getcwd()]) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/packages/autorest.python/test/unittests/storage_models/__init__.py b/packages/autorest.python/test/unittests/storage_models/__init__.py index 971c40a4499..e83340cab6f 100644 --- a/packages/autorest.python/test/unittests/storage_models/__init__.py +++ b/packages/autorest.python/test/unittests/storage_models/__init__.py @@ -44,35 +44,35 @@ ) __all__ = [ - 'StorageAccountCheckNameAvailabilityParameters', - 'CheckNameAvailabilityResult', - 'Sku', - 'CustomDomain', - 'EncryptionService', - 'EncryptionServices', - 'Encryption', - 'StorageAccountCreateParameters', - 'Endpoints', - 'StorageAccount', - 'StorageAccountKey', - 'StorageAccountListKeysResult', - 'StorageAccountRegenerateKeyParameters', - 'StorageAccountUpdateParameters', - 'UsageName', - 'Usage', - 'Resource', - 'AccountSasParameters', - 'ListAccountSasResponse', - 'ServiceSasParameters', - 'ListServiceSasResponse', - 'Reason', - 'SkuName', - 'SkuTier', - 'AccessTier', - 'Kind', - 'ProvisioningState', - 'AccountStatus', - 'KeyPermission', - 'UsageUnit', - 'HttpProtocol', + "StorageAccountCheckNameAvailabilityParameters", + "CheckNameAvailabilityResult", + "Sku", + "CustomDomain", + "EncryptionService", + "EncryptionServices", + "Encryption", + "StorageAccountCreateParameters", + "Endpoints", + "StorageAccount", + "StorageAccountKey", + "StorageAccountListKeysResult", + "StorageAccountRegenerateKeyParameters", + "StorageAccountUpdateParameters", + "UsageName", + "Usage", + "Resource", + "AccountSasParameters", + "ListAccountSasResponse", + "ServiceSasParameters", + "ListServiceSasResponse", + "Reason", + "SkuName", + "SkuTier", + "AccessTier", + "Kind", + "ProvisioningState", + "AccountStatus", + "KeyPermission", + "UsageUnit", + "HttpProtocol", ] diff --git a/packages/autorest.python/test/unittests/storage_models/account_sas_parameters.py b/packages/autorest.python/test/unittests/storage_models/account_sas_parameters.py index 6a302f60da9..3cf2942023a 100644 --- a/packages/autorest.python/test/unittests/storage_models/account_sas_parameters.py +++ b/packages/autorest.python/test/unittests/storage_models/account_sas_parameters.py @@ -50,24 +50,34 @@ class AccountSasParameters(Model): """ _validation = { - 'services': {'required': True}, - 'resource_types': {'required': True}, - 'permissions': {'required': True}, - 'shared_access_expiry_time': {'required': True}, + "services": {"required": True}, + "resource_types": {"required": True}, + "permissions": {"required": True}, + "shared_access_expiry_time": {"required": True}, } _attribute_map = { - 'services': {'key': 'signedServices', 'type': 'str'}, - 'resource_types': {'key': 'signedResourceTypes', 'type': 'str'}, - 'permissions': {'key': 'signedPermission', 'type': 'str'}, - 'ip_address_or_range': {'key': 'signedIp', 'type': 'str'}, - 'protocols': {'key': 'signedProtocol', 'type': 'HttpProtocol'}, - 'shared_access_start_time': {'key': 'signedStart', 'type': 'iso-8601'}, - 'shared_access_expiry_time': {'key': 'signedExpiry', 'type': 'iso-8601'}, - 'key_to_sign': {'key': 'keyToSign', 'type': 'str'}, + "services": {"key": "signedServices", "type": "str"}, + "resource_types": {"key": "signedResourceTypes", "type": "str"}, + "permissions": {"key": "signedPermission", "type": "str"}, + "ip_address_or_range": {"key": "signedIp", "type": "str"}, + "protocols": {"key": "signedProtocol", "type": "HttpProtocol"}, + "shared_access_start_time": {"key": "signedStart", "type": "iso-8601"}, + "shared_access_expiry_time": {"key": "signedExpiry", "type": "iso-8601"}, + "key_to_sign": {"key": "keyToSign", "type": "str"}, } - def __init__(self, services, resource_types, permissions, shared_access_expiry_time, ip_address_or_range=None, protocols=None, shared_access_start_time=None, key_to_sign=None): + def __init__( + self, + services, + resource_types, + permissions, + shared_access_expiry_time, + ip_address_or_range=None, + protocols=None, + shared_access_start_time=None, + key_to_sign=None, + ): self.services = services self.resource_types = resource_types self.permissions = permissions diff --git a/packages/autorest.python/test/unittests/storage_models/check_name_availability_result.py b/packages/autorest.python/test/unittests/storage_models/check_name_availability_result.py index c2117b58c56..e70572f9b3a 100644 --- a/packages/autorest.python/test/unittests/storage_models/check_name_availability_result.py +++ b/packages/autorest.python/test/unittests/storage_models/check_name_availability_result.py @@ -33,15 +33,15 @@ class CheckNameAvailabilityResult(Model): """ _validation = { - 'name_available': {'readonly': True}, - 'reason': {'readonly': True}, - 'message': {'readonly': True}, + "name_available": {"readonly": True}, + "reason": {"readonly": True}, + "message": {"readonly": True}, } _attribute_map = { - 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, - 'reason': {'key': 'reason', 'type': 'Reason'}, - 'message': {'key': 'message', 'type': 'str'}, + "name_available": {"key": "nameAvailable", "type": "bool"}, + "reason": {"key": "reason", "type": "Reason"}, + "message": {"key": "message", "type": "str"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/custom_domain.py b/packages/autorest.python/test/unittests/storage_models/custom_domain.py index 0e59fec5594..5e8a6f6be9f 100644 --- a/packages/autorest.python/test/unittests/storage_models/custom_domain.py +++ b/packages/autorest.python/test/unittests/storage_models/custom_domain.py @@ -25,12 +25,12 @@ class CustomDomain(Model): """ _validation = { - 'name': {'required': True}, + "name": {"required": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'use_sub_domain': {'key': 'useSubDomain', 'type': 'bool'}, + "name": {"key": "name", "type": "str"}, + "use_sub_domain": {"key": "useSubDomain", "type": "bool"}, } def __init__(self, name, use_sub_domain=None): diff --git a/packages/autorest.python/test/unittests/storage_models/encryption.py b/packages/autorest.python/test/unittests/storage_models/encryption.py index fa68ed3b12d..65700aa4a6e 100644 --- a/packages/autorest.python/test/unittests/storage_models/encryption.py +++ b/packages/autorest.python/test/unittests/storage_models/encryption.py @@ -28,12 +28,12 @@ class Encryption(Model): """ _validation = { - 'key_source': {'required': True, 'constant': True}, + "key_source": {"required": True, "constant": True}, } _attribute_map = { - 'services': {'key': 'services', 'type': 'EncryptionServices'}, - 'key_source': {'key': 'keySource', 'type': 'str'}, + "services": {"key": "services", "type": "EncryptionServices"}, + "key_source": {"key": "keySource", "type": "str"}, } key_source = "Microsoft.Storage" diff --git a/packages/autorest.python/test/unittests/storage_models/encryption_service.py b/packages/autorest.python/test/unittests/storage_models/encryption_service.py index 6ac356ae915..c2d7bbcd0ff 100644 --- a/packages/autorest.python/test/unittests/storage_models/encryption_service.py +++ b/packages/autorest.python/test/unittests/storage_models/encryption_service.py @@ -29,12 +29,12 @@ class EncryptionService(Model): """ _validation = { - 'last_enabled_time': {'readonly': True}, + "last_enabled_time": {"readonly": True}, } _attribute_map = { - 'enabled': {'key': 'enabled', 'type': 'bool'}, - 'last_enabled_time': {'key': 'lastEnabledTime', 'type': 'iso-8601'}, + "enabled": {"key": "enabled", "type": "bool"}, + "last_enabled_time": {"key": "lastEnabledTime", "type": "iso-8601"}, } def __init__(self, enabled=None): diff --git a/packages/autorest.python/test/unittests/storage_models/encryption_services.py b/packages/autorest.python/test/unittests/storage_models/encryption_services.py index 6f4430c02ce..68cf0a1bcc9 100644 --- a/packages/autorest.python/test/unittests/storage_models/encryption_services.py +++ b/packages/autorest.python/test/unittests/storage_models/encryption_services.py @@ -33,15 +33,15 @@ class EncryptionServices(Model): """ _validation = { - 'table': {'readonly': True}, - 'queue': {'readonly': True}, + "table": {"readonly": True}, + "queue": {"readonly": True}, } _attribute_map = { - 'blob': {'key': 'blob', 'type': 'EncryptionService'}, - 'file': {'key': 'file', 'type': 'EncryptionService'}, - 'table': {'key': 'table', 'type': 'EncryptionService'}, - 'queue': {'key': 'queue', 'type': 'EncryptionService'}, + "blob": {"key": "blob", "type": "EncryptionService"}, + "file": {"key": "file", "type": "EncryptionService"}, + "table": {"key": "table", "type": "EncryptionService"}, + "queue": {"key": "queue", "type": "EncryptionService"}, } def __init__(self, blob=None, file=None): diff --git a/packages/autorest.python/test/unittests/storage_models/endpoints.py b/packages/autorest.python/test/unittests/storage_models/endpoints.py index fe8913f2c96..77d4d768184 100644 --- a/packages/autorest.python/test/unittests/storage_models/endpoints.py +++ b/packages/autorest.python/test/unittests/storage_models/endpoints.py @@ -30,17 +30,17 @@ class Endpoints(Model): """ _validation = { - 'blob': {'readonly': True}, - 'queue': {'readonly': True}, - 'table': {'readonly': True}, - 'file': {'readonly': True}, + "blob": {"readonly": True}, + "queue": {"readonly": True}, + "table": {"readonly": True}, + "file": {"readonly": True}, } _attribute_map = { - 'blob': {'key': 'blob', 'type': 'str'}, - 'queue': {'key': 'queue', 'type': 'str'}, - 'table': {'key': 'table', 'type': 'str'}, - 'file': {'key': 'file', 'type': 'str'}, + "blob": {"key": "blob", "type": "str"}, + "queue": {"key": "queue", "type": "str"}, + "table": {"key": "table", "type": "str"}, + "file": {"key": "file", "type": "str"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/list_account_sas_response.py b/packages/autorest.python/test/unittests/storage_models/list_account_sas_response.py index 8c10604f6cd..a9b2e8d8f90 100644 --- a/packages/autorest.python/test/unittests/storage_models/list_account_sas_response.py +++ b/packages/autorest.python/test/unittests/storage_models/list_account_sas_response.py @@ -23,11 +23,11 @@ class ListAccountSasResponse(Model): """ _validation = { - 'account_sas_token': {'readonly': True}, + "account_sas_token": {"readonly": True}, } _attribute_map = { - 'account_sas_token': {'key': 'accountSasToken', 'type': 'str'}, + "account_sas_token": {"key": "accountSasToken", "type": "str"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/list_service_sas_response.py b/packages/autorest.python/test/unittests/storage_models/list_service_sas_response.py index 19fe124d43d..65f13ce9a59 100644 --- a/packages/autorest.python/test/unittests/storage_models/list_service_sas_response.py +++ b/packages/autorest.python/test/unittests/storage_models/list_service_sas_response.py @@ -24,11 +24,11 @@ class ListServiceSasResponse(Model): """ _validation = { - 'service_sas_token': {'readonly': True}, + "service_sas_token": {"readonly": True}, } _attribute_map = { - 'service_sas_token': {'key': 'serviceSasToken', 'type': 'str'}, + "service_sas_token": {"key": "serviceSasToken", "type": "str"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/resource.py b/packages/autorest.python/test/unittests/storage_models/resource.py index 0e1d39de61b..5e03b9bf15c 100644 --- a/packages/autorest.python/test/unittests/storage_models/resource.py +++ b/packages/autorest.python/test/unittests/storage_models/resource.py @@ -32,17 +32,17 @@ class Resource(Model): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, } def __init__(self, location=None, tags=None): diff --git a/packages/autorest.python/test/unittests/storage_models/service_sas_parameters.py b/packages/autorest.python/test/unittests/storage_models/service_sas_parameters.py index 749303b14ef..ccb559aeeeb 100644 --- a/packages/autorest.python/test/unittests/storage_models/service_sas_parameters.py +++ b/packages/autorest.python/test/unittests/storage_models/service_sas_parameters.py @@ -70,33 +70,53 @@ class ServiceSasParameters(Model): """ _validation = { - 'canonicalized_resource': {'required': True}, - 'resource': {'required': True}, - 'identifier': {'max_length': 64}, + "canonicalized_resource": {"required": True}, + "resource": {"required": True}, + "identifier": {"max_length": 64}, } _attribute_map = { - 'canonicalized_resource': {'key': 'canonicalizedResource', 'type': 'str'}, - 'resource': {'key': 'signedResource', 'type': 'str'}, - 'permissions': {'key': 'signedPermission', 'type': 'str'}, - 'ip_address_or_range': {'key': 'signedIp', 'type': 'str'}, - 'protocols': {'key': 'signedProtocol', 'type': 'HttpProtocol'}, - 'shared_access_start_time': {'key': 'signedStart', 'type': 'iso-8601'}, - 'shared_access_expiry_time': {'key': 'signedExpiry', 'type': 'iso-8601'}, - 'identifier': {'key': 'signedIdentifier', 'type': 'str'}, - 'partition_key_start': {'key': 'startPk', 'type': 'str'}, - 'partition_key_end': {'key': 'endPk', 'type': 'str'}, - 'row_key_start': {'key': 'startRk', 'type': 'str'}, - 'row_key_end': {'key': 'endRk', 'type': 'str'}, - 'key_to_sign': {'key': 'keyToSign', 'type': 'str'}, - 'cache_control': {'key': 'rscc', 'type': 'str'}, - 'content_disposition': {'key': 'rscd', 'type': 'str'}, - 'content_encoding': {'key': 'rsce', 'type': 'str'}, - 'content_language': {'key': 'rscl', 'type': 'str'}, - 'content_type': {'key': 'rsct', 'type': 'str'}, + "canonicalized_resource": {"key": "canonicalizedResource", "type": "str"}, + "resource": {"key": "signedResource", "type": "str"}, + "permissions": {"key": "signedPermission", "type": "str"}, + "ip_address_or_range": {"key": "signedIp", "type": "str"}, + "protocols": {"key": "signedProtocol", "type": "HttpProtocol"}, + "shared_access_start_time": {"key": "signedStart", "type": "iso-8601"}, + "shared_access_expiry_time": {"key": "signedExpiry", "type": "iso-8601"}, + "identifier": {"key": "signedIdentifier", "type": "str"}, + "partition_key_start": {"key": "startPk", "type": "str"}, + "partition_key_end": {"key": "endPk", "type": "str"}, + "row_key_start": {"key": "startRk", "type": "str"}, + "row_key_end": {"key": "endRk", "type": "str"}, + "key_to_sign": {"key": "keyToSign", "type": "str"}, + "cache_control": {"key": "rscc", "type": "str"}, + "content_disposition": {"key": "rscd", "type": "str"}, + "content_encoding": {"key": "rsce", "type": "str"}, + "content_language": {"key": "rscl", "type": "str"}, + "content_type": {"key": "rsct", "type": "str"}, } - def __init__(self, canonicalized_resource, resource, permissions=None, ip_address_or_range=None, protocols=None, shared_access_start_time=None, shared_access_expiry_time=None, identifier=None, partition_key_start=None, partition_key_end=None, row_key_start=None, row_key_end=None, key_to_sign=None, cache_control=None, content_disposition=None, content_encoding=None, content_language=None, content_type=None): + def __init__( + self, + canonicalized_resource, + resource, + permissions=None, + ip_address_or_range=None, + protocols=None, + shared_access_start_time=None, + shared_access_expiry_time=None, + identifier=None, + partition_key_start=None, + partition_key_end=None, + row_key_start=None, + row_key_end=None, + key_to_sign=None, + cache_control=None, + content_disposition=None, + content_encoding=None, + content_language=None, + content_type=None, + ): self.canonicalized_resource = canonicalized_resource self.resource = resource self.permissions = permissions diff --git a/packages/autorest.python/test/unittests/storage_models/sku.py b/packages/autorest.python/test/unittests/storage_models/sku.py index ab1c5251519..6d801be072a 100644 --- a/packages/autorest.python/test/unittests/storage_models/sku.py +++ b/packages/autorest.python/test/unittests/storage_models/sku.py @@ -31,13 +31,13 @@ class Sku(Model): """ _validation = { - 'name': {'required': True}, - 'tier': {'readonly': True}, + "name": {"required": True}, + "tier": {"readonly": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'SkuName'}, - 'tier': {'key': 'tier', 'type': 'SkuTier'}, + "name": {"key": "name", "type": "SkuName"}, + "tier": {"key": "tier", "type": "SkuTier"}, } def __init__(self, name): diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account.py b/packages/autorest.python/test/unittests/storage_models/storage_account.py index 9bd756b843a..a25c86ceb43 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account.py @@ -96,46 +96,46 @@ class StorageAccount(Resource): """ _validation = { - 'id': {'readonly': True}, - 'name': {'readonly': True}, - 'type': {'readonly': True}, - 'sku': {'readonly': True}, - 'kind': {'readonly': True}, - 'provisioning_state': {'readonly': True}, - 'primary_endpoints': {'readonly': True}, - 'primary_location': {'readonly': True}, - 'status_of_primary': {'readonly': True}, - 'last_geo_failover_time': {'readonly': True}, - 'secondary_location': {'readonly': True}, - 'status_of_secondary': {'readonly': True}, - 'creation_time': {'readonly': True}, - 'custom_domain': {'readonly': True}, - 'secondary_endpoints': {'readonly': True}, - 'encryption': {'readonly': True}, - 'access_tier': {'readonly': True}, + "id": {"readonly": True}, + "name": {"readonly": True}, + "type": {"readonly": True}, + "sku": {"readonly": True}, + "kind": {"readonly": True}, + "provisioning_state": {"readonly": True}, + "primary_endpoints": {"readonly": True}, + "primary_location": {"readonly": True}, + "status_of_primary": {"readonly": True}, + "last_geo_failover_time": {"readonly": True}, + "secondary_location": {"readonly": True}, + "status_of_secondary": {"readonly": True}, + "creation_time": {"readonly": True}, + "custom_domain": {"readonly": True}, + "secondary_endpoints": {"readonly": True}, + "encryption": {"readonly": True}, + "access_tier": {"readonly": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'kind': {'key': 'kind', 'type': 'Kind'}, - 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'ProvisioningState'}, - 'primary_endpoints': {'key': 'properties.primaryEndpoints', 'type': 'Endpoints'}, - 'primary_location': {'key': 'properties.primaryLocation', 'type': 'str'}, - 'status_of_primary': {'key': 'properties.statusOfPrimary', 'type': 'AccountStatus'}, - 'last_geo_failover_time': {'key': 'properties.lastGeoFailoverTime', 'type': 'iso-8601'}, - 'secondary_location': {'key': 'properties.secondaryLocation', 'type': 'str'}, - 'status_of_secondary': {'key': 'properties.statusOfSecondary', 'type': 'AccountStatus'}, - 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'}, - 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, - 'secondary_endpoints': {'key': 'properties.secondaryEndpoints', 'type': 'Endpoints'}, - 'encryption': {'key': 'properties.encryption', 'type': 'Encryption'}, - 'access_tier': {'key': 'properties.accessTier', 'type': 'AccessTier'}, - 'enable_https_traffic_only': {'key': 'properties.supportsHttpsTrafficOnly', 'type': 'bool'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "sku": {"key": "sku", "type": "Sku"}, + "kind": {"key": "kind", "type": "Kind"}, + "provisioning_state": {"key": "properties.provisioningState", "type": "ProvisioningState"}, + "primary_endpoints": {"key": "properties.primaryEndpoints", "type": "Endpoints"}, + "primary_location": {"key": "properties.primaryLocation", "type": "str"}, + "status_of_primary": {"key": "properties.statusOfPrimary", "type": "AccountStatus"}, + "last_geo_failover_time": {"key": "properties.lastGeoFailoverTime", "type": "iso-8601"}, + "secondary_location": {"key": "properties.secondaryLocation", "type": "str"}, + "status_of_secondary": {"key": "properties.statusOfSecondary", "type": "AccountStatus"}, + "creation_time": {"key": "properties.creationTime", "type": "iso-8601"}, + "custom_domain": {"key": "properties.customDomain", "type": "CustomDomain"}, + "secondary_endpoints": {"key": "properties.secondaryEndpoints", "type": "Endpoints"}, + "encryption": {"key": "properties.encryption", "type": "Encryption"}, + "access_tier": {"key": "properties.accessTier", "type": "AccessTier"}, + "enable_https_traffic_only": {"key": "properties.supportsHttpsTrafficOnly", "type": "bool"}, } def __init__(self, location=None, tags=None, enable_https_traffic_only=False): diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account_check_name_availability_parameters.py b/packages/autorest.python/test/unittests/storage_models/storage_account_check_name_availability_parameters.py index 23b3138a0b9..dec399404f3 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account_check_name_availability_parameters.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account_check_name_availability_parameters.py @@ -25,13 +25,13 @@ class StorageAccountCheckNameAvailabilityParameters(Model): """ _validation = { - 'name': {'required': True}, - 'type': {'required': True, 'constant': True}, + "name": {"required": True}, + "type": {"required": True, "constant": True}, } _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, } type = "Microsoft.Storage/storageAccounts" diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account_create_parameters.py b/packages/autorest.python/test/unittests/storage_models/storage_account_create_parameters.py index a5fe16521e2..4ec7e675c68 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account_create_parameters.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account_create_parameters.py @@ -55,23 +55,33 @@ class StorageAccountCreateParameters(Model): """ _validation = { - 'sku': {'required': True}, - 'kind': {'required': True}, - 'location': {'required': True}, + "sku": {"required": True}, + "kind": {"required": True}, + "location": {"required": True}, } _attribute_map = { - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'kind': {'key': 'kind', 'type': 'Kind'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, - 'encryption': {'key': 'properties.encryption', 'type': 'Encryption'}, - 'access_tier': {'key': 'properties.accessTier', 'type': 'AccessTier'}, - 'enable_https_traffic_only': {'key': 'properties.supportsHttpsTrafficOnly', 'type': 'bool'}, + "sku": {"key": "sku", "type": "Sku"}, + "kind": {"key": "kind", "type": "Kind"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "custom_domain": {"key": "properties.customDomain", "type": "CustomDomain"}, + "encryption": {"key": "properties.encryption", "type": "Encryption"}, + "access_tier": {"key": "properties.accessTier", "type": "AccessTier"}, + "enable_https_traffic_only": {"key": "properties.supportsHttpsTrafficOnly", "type": "bool"}, } - def __init__(self, sku, kind, location, tags=None, custom_domain=None, encryption=None, access_tier=None, enable_https_traffic_only=False): + def __init__( + self, + sku, + kind, + location, + tags=None, + custom_domain=None, + encryption=None, + access_tier=None, + enable_https_traffic_only=False, + ): self.sku = sku self.kind = kind self.location = location diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account_key.py b/packages/autorest.python/test/unittests/storage_models/storage_account_key.py index 7628b8bf6f4..cee67ef5341 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account_key.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account_key.py @@ -29,15 +29,15 @@ class StorageAccountKey(Model): """ _validation = { - 'key_name': {'readonly': True}, - 'value': {'readonly': True}, - 'permissions': {'readonly': True}, + "key_name": {"readonly": True}, + "value": {"readonly": True}, + "permissions": {"readonly": True}, } _attribute_map = { - 'key_name': {'key': 'keyName', 'type': 'str'}, - 'value': {'key': 'value', 'type': 'str'}, - 'permissions': {'key': 'permissions', 'type': 'KeyPermission'}, + "key_name": {"key": "keyName", "type": "str"}, + "value": {"key": "value", "type": "str"}, + "permissions": {"key": "permissions", "type": "KeyPermission"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account_list_keys_result.py b/packages/autorest.python/test/unittests/storage_models/storage_account_list_keys_result.py index d91c99de950..5f7de0c2524 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account_list_keys_result.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account_list_keys_result.py @@ -25,11 +25,11 @@ class StorageAccountListKeysResult(Model): """ _validation = { - 'keys': {'readonly': True}, + "keys": {"readonly": True}, } _attribute_map = { - 'keys': {'key': 'keys', 'type': '[StorageAccountKey]'}, + "keys": {"key": "keys", "type": "[StorageAccountKey]"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account_regenerate_key_parameters.py b/packages/autorest.python/test/unittests/storage_models/storage_account_regenerate_key_parameters.py index 71e405d978e..982edebbb76 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account_regenerate_key_parameters.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account_regenerate_key_parameters.py @@ -20,11 +20,11 @@ class StorageAccountRegenerateKeyParameters(Model): """ _validation = { - 'key_name': {'required': True}, + "key_name": {"required": True}, } _attribute_map = { - 'key_name': {'key': 'keyName', 'type': 'str'}, + "key_name": {"key": "keyName", "type": "str"}, } def __init__(self, key_name): diff --git a/packages/autorest.python/test/unittests/storage_models/storage_account_update_parameters.py b/packages/autorest.python/test/unittests/storage_models/storage_account_update_parameters.py index fb79aa43742..807826e1f2b 100644 --- a/packages/autorest.python/test/unittests/storage_models/storage_account_update_parameters.py +++ b/packages/autorest.python/test/unittests/storage_models/storage_account_update_parameters.py @@ -47,15 +47,23 @@ class StorageAccountUpdateParameters(Model): """ _attribute_map = { - 'sku': {'key': 'sku', 'type': 'Sku'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, - 'encryption': {'key': 'properties.encryption', 'type': 'Encryption'}, - 'access_tier': {'key': 'properties.accessTier', 'type': 'AccessTier'}, - 'enable_https_traffic_only': {'key': 'properties.supportsHttpsTrafficOnly', 'type': 'bool'}, + "sku": {"key": "sku", "type": "Sku"}, + "tags": {"key": "tags", "type": "{str}"}, + "custom_domain": {"key": "properties.customDomain", "type": "CustomDomain"}, + "encryption": {"key": "properties.encryption", "type": "Encryption"}, + "access_tier": {"key": "properties.accessTier", "type": "AccessTier"}, + "enable_https_traffic_only": {"key": "properties.supportsHttpsTrafficOnly", "type": "bool"}, } - def __init__(self, sku=None, tags=None, custom_domain=None, encryption=None, access_tier=None, enable_https_traffic_only=False): + def __init__( + self, + sku=None, + tags=None, + custom_domain=None, + encryption=None, + access_tier=None, + enable_https_traffic_only=False, + ): self.sku = sku self.tags = tags self.custom_domain = custom_domain diff --git a/packages/autorest.python/test/unittests/storage_models/usage.py b/packages/autorest.python/test/unittests/storage_models/usage.py index ca421a40238..cc6079325c9 100644 --- a/packages/autorest.python/test/unittests/storage_models/usage.py +++ b/packages/autorest.python/test/unittests/storage_models/usage.py @@ -35,17 +35,17 @@ class Usage(Model): """ _validation = { - 'unit': {'readonly': True}, - 'current_value': {'readonly': True}, - 'limit': {'readonly': True}, - 'name': {'readonly': True}, + "unit": {"readonly": True}, + "current_value": {"readonly": True}, + "limit": {"readonly": True}, + "name": {"readonly": True}, } _attribute_map = { - 'unit': {'key': 'unit', 'type': 'UsageUnit'}, - 'current_value': {'key': 'currentValue', 'type': 'int'}, - 'limit': {'key': 'limit', 'type': 'int'}, - 'name': {'key': 'name', 'type': 'UsageName'}, + "unit": {"key": "unit", "type": "UsageUnit"}, + "current_value": {"key": "currentValue", "type": "int"}, + "limit": {"key": "limit", "type": "int"}, + "name": {"key": "name", "type": "UsageName"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/storage_models/usage_name.py b/packages/autorest.python/test/unittests/storage_models/usage_name.py index 1a72c6d662e..9b7577824de 100644 --- a/packages/autorest.python/test/unittests/storage_models/usage_name.py +++ b/packages/autorest.python/test/unittests/storage_models/usage_name.py @@ -26,13 +26,13 @@ class UsageName(Model): """ _validation = { - 'value': {'readonly': True}, - 'localized_value': {'readonly': True}, + "value": {"readonly": True}, + "localized_value": {"readonly": True}, } _attribute_map = { - 'value': {'key': 'value', 'type': 'str'}, - 'localized_value': {'key': 'localizedValue', 'type': 'str'}, + "value": {"key": "value", "type": "str"}, + "localized_value": {"key": "localizedValue", "type": "str"}, } def __init__(self): diff --git a/packages/autorest.python/test/unittests/test_m2r.py b/packages/autorest.python/test/unittests/test_m2r.py index 59367344482..8ac1287dda3 100644 --- a/packages/autorest.python/test/unittests/test_m2r.py +++ b/packages/autorest.python/test/unittests/test_m2r.py @@ -55,7 +55,4 @@ def test_m2r_cycle(): def test_inline_html(): m2r = M2R(output_folder="") - assert ( - m2r.convert_to_rst("Dictionary of .") - == "Dictionary of :code:``." - ) + assert m2r.convert_to_rst("Dictionary of .") == "Dictionary of :code:``." diff --git a/packages/autorest.python/test/unittests/test_name_converter.py b/packages/autorest.python/test/unittests/test_name_converter.py index 1eb440420ee..1e650033e9b 100644 --- a/packages/autorest.python/test/unittests/test_name_converter.py +++ b/packages/autorest.python/test/unittests/test_name_converter.py @@ -6,16 +6,15 @@ from autorest.preprocess import PreProcessPlugin from autorest.preprocess.python_mappings import PadType + def pad_reserved_words(name: str, pad_type: PadType) -> str: return PreProcessPlugin(output_folder="").pad_reserved_words(name, pad_type) + def test_escaped_reserved_words(): expected_conversion_model = {"Self": "Self", "And": "AndModel"} for name in expected_conversion_model: - assert ( - pad_reserved_words(name, pad_type=PadType.MODEL) - == expected_conversion_model[name] - ) + assert pad_reserved_words(name, pad_type=PadType.MODEL) == expected_conversion_model[name] expected_conversion_method = { "self": "self", @@ -23,10 +22,7 @@ def test_escaped_reserved_words(): "content_type": "content_type", } for name in expected_conversion_method: - assert ( - pad_reserved_words(name, pad_type=PadType.METHOD) - == expected_conversion_method[name] - ) + assert pad_reserved_words(name, pad_type=PadType.METHOD) == expected_conversion_method[name] expected_conversion_parameter = { "content_type": "content_type_parameter", @@ -36,10 +32,7 @@ def test_escaped_reserved_words(): "continuation_token": "continuation_token_parameter", } for name in expected_conversion_parameter: - assert ( - pad_reserved_words(name, pad_type=PadType.PARAMETER) - == expected_conversion_parameter[name] - ) + assert pad_reserved_words(name, pad_type=PadType.PARAMETER) == expected_conversion_parameter[name] expected_conversion_enum = { "self": "self", @@ -47,7 +40,4 @@ def test_escaped_reserved_words(): "continuation_token": "continuation_token", } for name in expected_conversion_enum: - assert ( - pad_reserved_words(name, pad_type=PadType.ENUM) - == expected_conversion_enum[name] - ) + assert pad_reserved_words(name, pad_type=PadType.ENUM) == expected_conversion_enum[name] diff --git a/packages/autorest.python/test/unittests/test_parameter_ordering.py b/packages/autorest.python/test/unittests/test_parameter_ordering.py index 4fec6ea6176..8c68fd14863 100644 --- a/packages/autorest.python/test/unittests/test_parameter_ordering.py +++ b/packages/autorest.python/test/unittests/test_parameter_ordering.py @@ -101,6 +101,4 @@ def test_sort_required_and_non_required_parameters(): parameter_list = [optional_parameter, required_parameter] - assert [required_parameter, optional_parameter] == ParameterList( - {}, get_code_model(), parameter_list - ).method + assert [required_parameter, optional_parameter] == ParameterList({}, get_code_model(), parameter_list).method diff --git a/packages/autorest.python/test/unittests/test_serialization.py b/packages/autorest.python/test/unittests/test_serialization.py index 4a56579dba0..f123d67dc13 100644 --- a/packages/autorest.python/test/unittests/test_serialization.py +++ b/packages/autorest.python/test/unittests/test_serialization.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # @@ -23,7 +23,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import decimal from decimal import Decimal import sys @@ -39,16 +39,26 @@ from requests import Response -from storage_models.serialization import Model, last_restapi_key_transformer, full_restapi_key_transformer, rest_key_extractor +from storage_models.serialization import ( + Model, + last_restapi_key_transformer, + full_restapi_key_transformer, + rest_key_extractor, +) from storage_models.serialization import Serializer, Deserializer + # from azure.core.exceptions import ValidationError from azure.core.exceptions import SerializationError, DeserializationError -from azure.core.exceptions import SerializationError as AzureCoreSerializationError, DeserializationError as AzureCoreDeserializationError +from azure.core.exceptions import ( + SerializationError as AzureCoreSerializationError, + DeserializationError as AzureCoreDeserializationError, +) import storage_models import pytest + class Resource(Model): """Resource @@ -60,15 +70,15 @@ class Resource(Model): """ _validation = { - 'location': {'required': True}, + "location": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, } def __init__(self, location, id=None, name=None, type=None, tags=None, **kwargs): @@ -96,13 +106,13 @@ class GenericResource(Resource): _validation = {} _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'type': {'key': 'type', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, - 'tags': {'key': 'tags', 'type': '{str}'}, - 'plan': {'key': 'plan', 'type': 'Plan'}, - 'properties': {'key': 'properties', 'type': 'object'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "type": {"key": "type", "type": "str"}, + "location": {"key": "location", "type": "str"}, + "tags": {"key": "tags", "type": "{str}"}, + "plan": {"key": "plan", "type": "Plan"}, + "properties": {"key": "properties", "type": "object"}, } def __init__(self, location, id=None, name=None, type=None, tags=None, plan=None, properties=None): @@ -110,65 +120,70 @@ def __init__(self, location, id=None, name=None, type=None, tags=None, plan=None self.plan = plan self.properties = properties + class TestModelDeserialization(unittest.TestCase): def setUp(self): - self.d = Deserializer({'Resource':Resource, 'GenericResource':GenericResource}) + self.d = Deserializer({"Resource": Resource, "GenericResource": GenericResource}) return super(TestModelDeserialization, self).setUp() - @pytest.mark.skip("validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428") + @pytest.mark.skip( + "validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428" + ) def test_model_kwargs(self): class MyModel(Model): _validation = { - 'id': {'readonly': True}, - 'name': {'required': True}, + "id": {"readonly": True}, + "name": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, } + def __init__(self, **kwargs): super(MyModel, self).__init__(**kwargs) self.id = None - self.name = kwargs.get('name', None) - self.location = kwargs.get('location', None) + self.name = kwargs.get("name", None) + self.location = kwargs.get("location", None) validation = MyModel().validate() self.assertEqual(str(validation[0]), "Parameter 'MyModel.name' can not be None.") - @unittest.skipIf(sys.version_info < (3,4), "assertLogs not supported before 3.4") + @unittest.skipIf(sys.version_info < (3, 4), "assertLogs not supported before 3.4") def test_model_kwargs_logs(self): class MyModel(Model): _validation = { - 'id': {'readonly': True}, - 'name': {'required': True}, + "id": {"readonly": True}, + "name": {"required": True}, } _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'name': {'key': 'name', 'type': 'str'}, - 'location': {'key': 'location', 'type': 'str'}, + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "location": {"key": "location", "type": "str"}, } + def __init__(self, **kwargs): super(MyModel, self).__init__(**kwargs) self.id = None - self.name = kwargs.get('name', None) - self.location = kwargs.get('location', None) + self.name = kwargs.get("name", None) + self.location = kwargs.get("location", None) - with self.assertLogs('storage_models.serialization', level='WARNING') as cm: - MyModel(name="test", id="123") # Should log that id is readonly + with self.assertLogs("storage_models.serialization", level="WARNING") as cm: + MyModel(name="test", id="123") # Should log that id is readonly self.assertEqual(len(cm.output), 1) self.assertIn("attribute id", cm.output[0]) self.assertIn("Readonly", cm.output[0]) - with self.assertLogs('storage_models.serialization', level='WARNING') as cm: - MyModel(something="ioprez") # Should log that this is unknown + with self.assertLogs("storage_models.serialization", level="WARNING") as cm: + MyModel(something="ioprez") # Should log that this is unknown self.assertEqual(len(cm.output), 1) self.assertIn("not a known attribute", cm.output[0]) - @unittest.skipIf(sys.version_info < (3,4), "assertLogs not supported before 3.4") + @unittest.skipIf(sys.version_info < (3, 4), "assertLogs not supported before 3.4") def test_empty_enum_logs(self): class StatusType(str, Enum): success = "success" @@ -177,63 +192,53 @@ class StatusType(str, Enum): d = Deserializer({"StatusType": StatusType}) with self.assertRaises(AssertionError): - with self.assertLogs('storage_models.serialization', level='WARNING') as cm: + with self.assertLogs("storage_models.serialization", level="WARNING") as cm: result = d(StatusType, "failed") self.assertEqual(len(cm.output), 0) self.assertEqual(result, StatusType.failed) with self.assertRaises(AssertionError): - with self.assertLogs('storage_models.serialization', level='WARNING') as cm: + with self.assertLogs("storage_models.serialization", level="WARNING") as cm: result = d(StatusType, None) self.assertEqual(len(cm.output), 0) self.assertEqual(result, None) - with self.assertLogs('storage_models.serialization', level='WARNING') as cm: + with self.assertLogs("storage_models.serialization", level="WARNING") as cm: result = d(StatusType, "aborted") - self.assertEqual(result, 'aborted') + self.assertEqual(result, "aborted") self.assertEqual(len(cm.output), 1) self.assertTrue("Deserializer is not able to find aborted as valid enum" in cm.output[0]) def test_response(self): data = { - "properties": { - "platformUpdateDomainCount": 5, - "platformFaultDomainCount": 3, - "virtualMachines": [] - }, - "id": "/subscriptions/abc-def-ghi-jklmnop/resourceGroups/test_mgmt_resource_test_resourcesea/providers/Microsoft.Compute/availabilitySets/pytest", - "name": "pytest", - "type": "Microsoft.Compute/availabilitySets", - "location": "westus" + "properties": {"platformUpdateDomainCount": 5, "platformFaultDomainCount": 3, "virtualMachines": []}, + "id": "/subscriptions/abc-def-ghi-jklmnop/resourceGroups/test_mgmt_resource_test_resourcesea/providers/Microsoft.Compute/availabilitySets/pytest", + "name": "pytest", + "type": "Microsoft.Compute/availabilitySets", + "location": "westus", } - model = self.d('GenericResource', json.dumps(data), 'application/json') - self.assertEqual(model.properties['platformFaultDomainCount'], 3) - self.assertEqual(model.location, 'westus') + model = self.d("GenericResource", json.dumps(data), "application/json") + self.assertEqual(model.properties["platformFaultDomainCount"], 3) + self.assertEqual(model.location, "westus") + class TestRuntimeSerialized(unittest.TestCase): class TestObj(Model): _attribute_map = { - 'attr_a': {'key':'id', 'type':'str'}, - 'attr_b': {'key':'AttrB', 'type':'int'}, - 'attr_c': {'key':'Key_C', 'type': 'bool'}, - 'attr_d': {'key':'AttrD', 'type':'[int]'}, - 'attr_e': {'key':'AttrE', 'type': '{float}'}, - 'attr_f': {'key':'AttrF', 'type': 'duration'}, - 'attr_g': {'key':'properties.AttrG', 'type':'str'}, + "attr_a": {"key": "id", "type": "str"}, + "attr_b": {"key": "AttrB", "type": "int"}, + "attr_c": {"key": "Key_C", "type": "bool"}, + "attr_d": {"key": "AttrD", "type": "[int]"}, + "attr_e": {"key": "AttrE", "type": "{float}"}, + "attr_f": {"key": "AttrF", "type": "duration"}, + "attr_g": {"key": "properties.AttrG", "type": "str"}, } - def __init__(self, - attr_a=None, - attr_b=None, - attr_c=None, - attr_d=None, - attr_e=None, - attr_f=None, - attr_g=None): + def __init__(self, attr_a=None, attr_b=None, attr_c=None, attr_d=None, attr_e=None, attr_f=None, attr_g=None): self.attr_a = attr_a self.attr_b = attr_b @@ -247,10 +252,12 @@ def __str__(self): return "Test_Object" def setUp(self): - self.s = Serializer({'TestObj': self.TestObj}) + self.s = Serializer({"TestObj": self.TestObj}) return super(TestRuntimeSerialized, self).setUp() - @pytest.mark.skip("validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428") + @pytest.mark.skip( + "validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428" + ) def test_validation_type(self): # https://github.com/Azure/msrest-for-python/issues/85 s = Serializer() @@ -261,19 +268,18 @@ def test_validation_type(self): class TestValidationObj(Model): _attribute_map = { - 'attr_a': {'key':'id', 'type':'int'}, + "attr_a": {"key": "id", "type": "int"}, } _validation = { - 'attr_a': {'maximum': 4294967295, 'minimum': 1}, + "attr_a": {"maximum": 4294967295, "minimum": 1}, } - test_obj = TestValidationObj() test_obj.attr_a = 186 errors_found = test_obj.validate() assert not errors_found - test_obj.attr_a = '186' + test_obj.attr_a = "186" errors_found = test_obj.validate() assert not errors_found @@ -290,7 +296,7 @@ def test_validation_flag(self): test_obj = self.TestObj() self.TestObj._validation = { - 'attr_b': {'required': True}, + "attr_b": {"required": True}, } test_obj.attr_b = None @@ -301,7 +307,7 @@ def test_validation_flag(self): s.query("filter", "", "str", min_length=666) s.url("filter", "", "str", min_length=666) s.header("filter", "", "str", min_length=666) - s.body(test_obj, 'TestObj') + s.body(test_obj, "TestObj") def test_serialize_query(self): s = Serializer() @@ -310,52 +316,74 @@ def test_serialize_query(self): assert s.query("filter", "boo,bar", "str", skip_quote=True) == "boo,bar" assert s.query("filter", 12, "int") == "12" - assert s.query("filter", [1, 2, 3], "[int]") == ['1', '2', '3'] + assert s.query("filter", [1, 2, 3], "[int]") == ["1", "2", "3"] assert s.query("filter", [1, 2, 3], "[int]", div=",") == "1,2,3" - assert s.query("filter", ['a', 'b', 'c'], "[str]") == ['a', 'b', 'c'] - assert s.query("filter", ['a', 'b', 'c'], "[str]", div=",") == "a,b,c" - assert s.query("filter", ['a', None, 'c'], "[str]", div=",") == "a,,c" - assert s.query("filter", [',', ',', ','], "[str]", div=",") == "%2C,%2C,%2C" - assert s.query("filter", [',', ',', ','], "[str]", div="|", skip_quote=True) == ",|,|," + assert s.query("filter", ["a", "b", "c"], "[str]") == ["a", "b", "c"] + assert s.query("filter", ["a", "b", "c"], "[str]", div=",") == "a,b,c" + assert s.query("filter", ["a", None, "c"], "[str]", div=",") == "a,,c" + assert s.query("filter", [",", ",", ","], "[str]", div=",") == "%2C,%2C,%2C" + assert s.query("filter", [",", ",", ","], "[str]", div="|", skip_quote=True) == ",|,|," def test_serialize_query_datetime_list(self): s = Serializer() - assert s.query("filter", [ - datetime(2022, 8, 26, 17, 38, 0), - datetime(2022, 8, 26, 18, 38, 0), - datetime(2022, 8, 26, 19, 38, 0), - ], "[iso-8601]", - ) == ['2022-08-26T17%3A38%3A00.000Z', '2022-08-26T18%3A38%3A00.000Z', '2022-08-26T19%3A38%3A00.000Z'] - assert s.query("filter", [ - datetime(2022, 8, 26, 17, 38, 0), - datetime(2022, 8, 26, 18, 38, 0), - datetime(2022, 8, 26, 19, 38, 0), - ], "[iso-8601]", div="," - ) == "2022-08-26T17%3A38%3A00.000Z,2022-08-26T18%3A38%3A00.000Z,2022-08-26T19%3A38%3A00.000Z" - assert s.query("filter", [ - datetime(2022, 8, 26, 17, 38, 0), - datetime(2022, 8, 26, 18, 38, 0), - datetime(2022, 8, 26, 19, 38, 0), - ], "[iso-8601]", skip_quote=True - ) == ['2022-08-26T17:38:00.000Z', '2022-08-26T18:38:00.000Z', '2022-08-26T19:38:00.000Z'] - assert s.query("filter", [ - datetime(2022, 8, 26, 17, 38, 0), - datetime(2022, 8, 26, 18, 38, 0), - datetime(2022, 8, 26, 19, 38, 0), - ], "[iso-8601]", div=",", skip_quote=True - ) == "2022-08-26T17:38:00.000Z,2022-08-26T18:38:00.000Z,2022-08-26T19:38:00.000Z" + assert s.query( + "filter", + [ + datetime(2022, 8, 26, 17, 38, 0), + datetime(2022, 8, 26, 18, 38, 0), + datetime(2022, 8, 26, 19, 38, 0), + ], + "[iso-8601]", + ) == ["2022-08-26T17%3A38%3A00.000Z", "2022-08-26T18%3A38%3A00.000Z", "2022-08-26T19%3A38%3A00.000Z"] + assert ( + s.query( + "filter", + [ + datetime(2022, 8, 26, 17, 38, 0), + datetime(2022, 8, 26, 18, 38, 0), + datetime(2022, 8, 26, 19, 38, 0), + ], + "[iso-8601]", + div=",", + ) + == "2022-08-26T17%3A38%3A00.000Z,2022-08-26T18%3A38%3A00.000Z,2022-08-26T19%3A38%3A00.000Z" + ) + assert s.query( + "filter", + [ + datetime(2022, 8, 26, 17, 38, 0), + datetime(2022, 8, 26, 18, 38, 0), + datetime(2022, 8, 26, 19, 38, 0), + ], + "[iso-8601]", + skip_quote=True, + ) == ["2022-08-26T17:38:00.000Z", "2022-08-26T18:38:00.000Z", "2022-08-26T19:38:00.000Z"] + assert ( + s.query( + "filter", + [ + datetime(2022, 8, 26, 17, 38, 0), + datetime(2022, 8, 26, 18, 38, 0), + datetime(2022, 8, 26, 19, 38, 0), + ], + "[iso-8601]", + div=",", + skip_quote=True, + ) + == "2022-08-26T17:38:00.000Z,2022-08-26T18:38:00.000Z,2022-08-26T19:38:00.000Z" + ) def test_serialize_custom_model(self): class CustomSample(Model): _validation = { - 'a': {'required': True}, + "a": {"required": True}, } _attribute_map = { - 'a': {'key': 'a', 'type': 'str'}, + "a": {"key": "a", "type": "str"}, } def __init__(self, a): @@ -367,14 +395,14 @@ def __init__(self, a): assert serialized is not None assert isinstance(serialized, dict) - assert serialized['a'] == "helloworld" + assert serialized["a"] == "helloworld" def test_serialize_direct_model(self): testobj = self.TestObj() testobj.attr_a = "myid" testobj.attr_b = 42 testobj.attr_c = True - testobj.attr_d = [1,2,3] + testobj.attr_d = [1, 2, 3] testobj.attr_e = {"pi": 3.14} testobj.attr_f = timedelta(1) testobj.attr_g = "RecursiveObject" @@ -384,12 +412,10 @@ def test_serialize_direct_model(self): "id": "myid", "AttrB": 42, "Key_C": True, - "AttrD": [1,2,3], + "AttrD": [1, 2, 3], "AttrE": {"pi": 3.14}, "AttrF": "P1D", - "properties": { - "AttrG": "RecursiveObject" - } + "properties": {"AttrG": "RecursiveObject"}, } self.assertDictEqual(expected, serialized) @@ -398,10 +424,10 @@ def test_serialize_direct_model(self): "attr_a": "myid", "attr_b": 42, "attr_c": True, - "attr_d": [1,2,3], + "attr_d": [1, 2, 3], "attr_e": {"pi": 3.14}, "attr_f": "P1D", - "attr_g": "RecursiveObject" + "attr_g": "RecursiveObject", } self.assertDictEqual(expected, json.loads(jsonable)) @@ -410,22 +436,22 @@ def test_serialize_direct_model(self): "id": "myid", "AttrB": 42, "Key_C": True, - "AttrD": [1,2,3], + "AttrD": [1, 2, 3], "AttrE": {"pi": 3.14}, "AttrF": "P1D", - "AttrG": "RecursiveObject" + "AttrG": "RecursiveObject", } self.assertDictEqual(expected, json.loads(jsonable)) - jsonable = json.dumps(testobj.as_dict(key_transformer=lambda x,y,z: (x+"XYZ", z))) + jsonable = json.dumps(testobj.as_dict(key_transformer=lambda x, y, z: (x + "XYZ", z))) expected = { "attr_aXYZ": "myid", "attr_bXYZ": 42, "attr_cXYZ": True, - "attr_dXYZ": [1,2,3], + "attr_dXYZ": [1, 2, 3], "attr_eXYZ": {"pi": 3.14}, "attr_fXYZ": "P1D", - "attr_gXYZ": "RecursiveObject" + "attr_gXYZ": "RecursiveObject", } self.assertDictEqual(expected, json.loads(jsonable)) @@ -440,35 +466,38 @@ def value_override(attr, attr_desc, value): "id": "myid", "AttrB": 43, "Key_C": True, - "AttrD": [1,2,3], + "AttrD": [1, 2, 3], "AttrE": {"pi": 3.14}, "AttrF": "P1D", - "AttrG": "RecursiveObject" + "AttrG": "RecursiveObject", } self.assertDictEqual(expected, json.loads(jsonable)) - - @pytest.mark.skip("validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428") + @pytest.mark.skip( + "validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428" + ) def test_validate(self): # Assert not necessary, should not raise exception self.s.validate("simplestring", "StringForLog", pattern="^[a-z]+$") - self.s.validate(u"UTF8ééééé", "StringForLog", pattern=r"^[\w]+$") + self.s.validate("UTF8ééééé", "StringForLog", pattern=r"^[\w]+$") - @pytest.mark.skip("validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428") + @pytest.mark.skip( + "validation is not priority: https://github.com/Azure/autorest.python/pull/2002#discussion_r1256223428" + ) def test_model_validate(self): class TestObj(Model): _validation = { - 'name': {'min_length': 3}, - 'display_names': {'min_items': 2}, + "name": {"min_length": 3}, + "display_names": {"min_items": 2}, } _attribute_map = { - 'name': {'key':'name', 'type':'str'}, - 'rec_list': {'key':'rec_list', 'type':'[[TestObj]]'}, - 'rec_dict': {'key':'rec_dict', 'type':'{{TestObj}}'}, - 'display_names': {'key': 'display_names', 'type': '[str]'}, - 'obj': {'key':'obj', 'type':'TestObj'}, + "name": {"key": "name", "type": "str"}, + "rec_list": {"key": "rec_list", "type": "[[TestObj]]"}, + "rec_dict": {"key": "rec_dict", "type": "{{TestObj}}"}, + "display_names": {"key": "display_names", "type": "[str]"}, + "obj": {"key": "obj", "type": "TestObj"}, } def __init__(self, name): @@ -487,36 +516,29 @@ def __init__(self, name): broken_rules = obj.validate() self.assertEqual(5, len(broken_rules)) str_broken_rules = [str(v) for v in broken_rules] - self.assertIn( - "Parameter 'TestObj.name' must have length greater than 3.", - str_broken_rules - ) - self.assertIn( - "Parameter 'TestObj.display_names' must contain at least 2 items.", - str_broken_rules - ) + self.assertIn("Parameter 'TestObj.name' must have length greater than 3.", str_broken_rules) + self.assertIn("Parameter 'TestObj.display_names' must contain at least 2 items.", str_broken_rules) def test_obj_serialize_none(self): - """Test that serialize None in object is still None. - """ - obj = self.s.serialize_object({'test': None}) - self.assertIsNone(obj['test']) + """Test that serialize None in object is still None.""" + obj = self.s.serialize_object({"test": None}) + self.assertIsNone(obj["test"]) def test_obj_with_malformed_map(self): """ Test serializing an object with a malformed attribute_map. """ - test_obj = type("BadTestObj", (Model,), {"_attribute_map":None}) + test_obj = type("BadTestObj", (Model,), {"_attribute_map": None}) with self.assertRaises(SerializationError): self.s._serialize(test_obj) - test_obj._attribute_map = {"attr":"val"} + test_obj._attribute_map = {"attr": "val"} with self.assertRaises(SerializationError): self.s._serialize(test_obj) - test_obj._attribute_map = {"attr":{"val":1}} + test_obj._attribute_map = {"attr": {"val": 1}} with self.assertRaises(SerializationError): self.s._serialize(test_obj) @@ -525,8 +547,8 @@ def test_obj_with_mismatched_map(self): """ Test serializing an object with mismatching attributes and map. """ - test_obj = type("BadTestObj", (Model,), {"_attribute_map":None}) - test_obj._attribute_map = {"abc":{"key":"ABC", "type":"str"}} + test_obj = type("BadTestObj", (Model,), {"_attribute_map": None}) + test_obj._attribute_map = {"abc": {"key": "ABC", "type": "str"}} with self.assertRaises(SerializationError): self.s._serialize(test_obj) @@ -536,10 +558,9 @@ def test_attr_enum(self): Test serializing with Enum. """ - test_obj = type("TestEnumObj", (Model,), {"_attribute_map":None}) - test_obj._attribute_map = { - "abc":{"key":"ABC", "type":"TestEnum"} - } + test_obj = type("TestEnumObj", (Model,), {"_attribute_map": None}) + test_obj._attribute_map = {"abc": {"key": "ABC", "type": "TestEnum"}} + class TestEnum(Enum): val = "Value" @@ -547,48 +568,30 @@ class TestEnum(Enum): t.abc = TestEnum.val serialized = self.s._serialize(t) - expected = { - "ABC": "Value" - } + expected = {"ABC": "Value"} self.assertEqual(expected, serialized) class TestEnum2(Enum): val2 = "Value2" + t.abc = TestEnum2.val2 - serializer = Serializer({ - 'TestEnum': TestEnum, - 'TestEnum2': TestEnum2 - }) + serializer = Serializer({"TestEnum": TestEnum, "TestEnum2": TestEnum2}) with self.assertRaises(SerializationError): serializer._serialize(t) - serializer = Serializer({ - 'TestEnumObj': test_obj, - 'TestEnum': TestEnum - }) - serialized = serializer.body({ - 'abc': TestEnum.val - }, 'TestEnumObj') - expected = { - 'ABC': 'Value' - } + serializer = Serializer({"TestEnumObj": test_obj, "TestEnum": TestEnum}) + serialized = serializer.body({"abc": TestEnum.val}, "TestEnumObj") + expected = {"ABC": "Value"} self.assertEqual(expected, serialized) # model-as-string=True - test_obj._attribute_map = { - "abc":{"key":"ABC", "type":"str"} - } - serialized = serializer.body({ - 'abc': TestEnum.val - }, 'TestEnumObj') - expected = { - 'ABC': 'Value' - } + test_obj._attribute_map = {"abc": {"key": "ABC", "type": "str"}} + serialized = serializer.body({"abc": TestEnum.val}, "TestEnumObj") + expected = {"ABC": "Value"} self.assertEqual(expected, serialized) - def test_attr_none(self): """ Test serializing an object with None attributes. @@ -597,7 +600,7 @@ def test_attr_none(self): message = self.s._serialize(test_obj) self.assertIsInstance(message, dict) - self.assertFalse('id' in message) + self.assertFalse("id" in message) def test_attr_int(self): """ @@ -605,7 +608,7 @@ def test_attr_int(self): """ test_obj = self.TestObj() self.TestObj._validation = { - 'attr_b': {'required': True}, + "attr_b": {"required": True}, } test_obj.attr_b = None @@ -618,12 +621,12 @@ def test_attr_int(self): test_obj.attr_b = 25 message = self.s._serialize(test_obj) - self.assertEqual(message['AttrB'], int(test_obj.attr_b)) + self.assertEqual(message["AttrB"], int(test_obj.attr_b)) test_obj.attr_b = "34534" message = self.s._serialize(test_obj) - self.assertEqual(message['AttrB'], int(test_obj.attr_b)) + self.assertEqual(message["AttrB"], int(test_obj.attr_b)) test_obj.attr_b = "NotANumber" @@ -638,7 +641,7 @@ def test_attr_str(self): """ test_obj = self.TestObj() self.TestObj._validation = { - 'attr_a': {'required': True}, + "attr_a": {"required": True}, } test_obj.attr_a = None @@ -652,22 +655,22 @@ def test_attr_str(self): test_obj.attr_a = "TestString" message = self.s._serialize(test_obj) - self.assertEqual(message['id'], str(test_obj.attr_a)) + self.assertEqual(message["id"], str(test_obj.attr_a)) test_obj.attr_a = 1234 message = self.s._serialize(test_obj) - self.assertEqual(message['id'], str(test_obj.attr_a)) + self.assertEqual(message["id"], str(test_obj.attr_a)) test_obj.attr_a = list() message = self.s._serialize(test_obj) - self.assertEqual(message['id'], str(test_obj.attr_a)) + self.assertEqual(message["id"], str(test_obj.attr_a)) test_obj.attr_a = [1] message = self.s._serialize(test_obj) - self.assertEqual(message['id'], str(test_obj.attr_a)) + self.assertEqual(message["id"], str(test_obj.attr_a)) def test_attr_bool(self): """ @@ -677,22 +680,22 @@ def test_attr_bool(self): test_obj.attr_c = True message = self.s._serialize(test_obj) - self.assertEqual(message['Key_C'], True) + self.assertEqual(message["Key_C"], True) test_obj.attr_c = "" message = self.s._serialize(test_obj) - self.assertTrue('Key_C' in message) + self.assertTrue("Key_C" in message) test_obj.attr_c = None message = self.s._serialize(test_obj) - self.assertFalse('Key_C' in message) + self.assertFalse("Key_C" in message) test_obj.attr_c = "NotEmpty" message = self.s._serialize(test_obj) - self.assertEqual(message['Key_C'], True) + self.assertEqual(message["Key_C"], True) def test_attr_sequence(self): """ @@ -700,11 +703,11 @@ def test_attr_sequence(self): """ test_obj = ["A", "B", "C"] - output = self.s._serialize(test_obj, '[str]', div='|') + output = self.s._serialize(test_obj, "[str]", div="|") self.assertEqual(output, "|".join(test_obj)) - test_obj = [1,2,3] - output = self.s._serialize(test_obj, '[str]', div=',') + test_obj = [1, 2, 3] + output = self.s._serialize(test_obj, "[str]", div=",") self.assertEqual(output, ",".join([str(i) for i in test_obj])) def test_attr_duration(self): @@ -720,9 +723,7 @@ def test_attr_duration(self): test_obj = self.TestObj() test_obj.attr_f = isodate.parse_duration("P3Y6M4DT12H30M5S") - message = self.s.body({ - "attr_f": isodate.parse_duration("P3Y6M4DT12H30M5S")}, - 'TestObj') + message = self.s.body({"attr_f": isodate.parse_duration("P3Y6M4DT12H30M5S")}, "TestObj") self.assertEqual("P3Y6M4DT12H30M5S", message["AttrF"]) def test_attr_list_simple(self): @@ -733,19 +734,19 @@ def test_attr_list_simple(self): test_obj.attr_d = [] message = self.s._serialize(test_obj) - self.assertEqual(message['AttrD'], test_obj.attr_d) + self.assertEqual(message["AttrD"], test_obj.attr_d) - test_obj.attr_d = [1,2,3] + test_obj.attr_d = [1, 2, 3] message = self.s._serialize(test_obj) - self.assertEqual(message['AttrD'], test_obj.attr_d) + self.assertEqual(message["AttrD"], test_obj.attr_d) - test_obj.attr_d = ["1","2","3"] + test_obj.attr_d = ["1", "2", "3"] message = self.s._serialize(test_obj) - self.assertEqual(message['AttrD'], [int(i) for i in test_obj.attr_d]) + self.assertEqual(message["AttrD"], [int(i) for i in test_obj.attr_d]) - test_obj.attr_d = ["test","test2","test3"] + test_obj.attr_d = ["test", "test2", "test3"] with self.assertRaises(SerializationError): self.s._serialize(test_obj) @@ -758,35 +759,31 @@ def test_attr_list_simple(self): def test_empty_list(self): input = [] - output = self.s._serialize(input, '[str]') + output = self.s._serialize(input, "[str]") self.assertEqual(output, input) def test_attr_list_complex(self): """ Test serializing an object with a list of complex objects as an attribute. """ - list_obj = type("ListObj", (Model,), {"_attribute_map":None, - "_validation":{}, - "abc":None}) - list_obj._attribute_map = {"abc":{"key":"ABC", "type":"int"}} + list_obj = type("ListObj", (Model,), {"_attribute_map": None, "_validation": {}, "abc": None}) + list_obj._attribute_map = {"abc": {"key": "ABC", "type": "int"}} list_obj.abc = "123" - test_obj = type("CmplxTestObj", (Model,), {"_attribute_map":None, - "_validation":{}, - "test_list":None}) + test_obj = type("CmplxTestObj", (Model,), {"_attribute_map": None, "_validation": {}, "test_list": None}) - test_obj._attribute_map = {"test_list":{"key":"_list", "type":"[ListObj]"}} + test_obj._attribute_map = {"test_list": {"key": "_list", "type": "[ListObj]"}} test_obj.test_list = [list_obj] message = self.s._serialize(test_obj) - self.assertEqual(message, {'_list':[{'ABC':123}]}) + self.assertEqual(message, {"_list": [{"ABC": 123}]}) - list_obj = type("BadListObj", (Model,), {"map":None}) - test_obj._attribute_map = {"test_list":{"key":"_list", "type":"[BadListObj]"}} + list_obj = type("BadListObj", (Model,), {"map": None}) + test_obj._attribute_map = {"test_list": {"key": "_list", "type": "[BadListObj]"}} test_obj.test_list = [list_obj] s = self.s._serialize(test_obj) - self.assertEqual(s, {'_list':[{}]}) + self.assertEqual(s, {"_list": [{}]}) def test_attr_dict_simple(self): """ @@ -797,12 +794,12 @@ def test_attr_dict_simple(self): test_obj.attr_e = {"value": 3.14} message = self.s._serialize(test_obj) - self.assertEqual(message['AttrE']['value'], float(test_obj.attr_e["value"])) + self.assertEqual(message["AttrE"]["value"], float(test_obj.attr_e["value"])) test_obj.attr_e = {1: "3.14"} message = self.s._serialize(test_obj) - self.assertEqual(message['AttrE']['1'], float(test_obj.attr_e[1])) + self.assertEqual(message["AttrE"]["1"], float(test_obj.attr_e[1])) test_obj.attr_e = "NotADict" @@ -820,139 +817,134 @@ def test_attr_dict_simple(self): def test_serialize_datetime(self): - date_obj = isodate.parse_datetime('2015-01-01T00:00:00') + date_obj = isodate.parse_datetime("2015-01-01T00:00:00") date_str = Serializer.serialize_iso(date_obj) - self.assertEqual(date_str, '2015-01-01T00:00:00.000Z') + self.assertEqual(date_str, "2015-01-01T00:00:00.000Z") - date_obj = isodate.parse_datetime('1999-12-31T23:59:59-12:00') + date_obj = isodate.parse_datetime("1999-12-31T23:59:59-12:00") date_str = Serializer.serialize_iso(date_obj) - self.assertEqual(date_str, '2000-01-01T11:59:59.000Z') + self.assertEqual(date_str, "2000-01-01T11:59:59.000Z") with self.assertRaises(SerializationError): - date_obj = isodate.parse_datetime('9999-12-31T23:59:59-12:00') + date_obj = isodate.parse_datetime("9999-12-31T23:59:59-12:00") date_str = Serializer.serialize_iso(date_obj) with self.assertRaises(SerializationError): - date_obj = isodate.parse_datetime('0001-01-01T00:00:00+23:59') + date_obj = isodate.parse_datetime("0001-01-01T00:00:00+23:59") date_str = Serializer.serialize_iso(date_obj) - date_obj = isodate.parse_datetime("2015-06-01T16:10:08.0121-07:00") date_str = Serializer.serialize_iso(date_obj) - self.assertEqual(date_str, '2015-06-01T23:10:08.0121Z') + self.assertEqual(date_str, "2015-06-01T23:10:08.0121Z") date_obj = datetime.min date_str = Serializer.serialize_iso(date_obj) - self.assertEqual(date_str, '0001-01-01T00:00:00.000Z') + self.assertEqual(date_str, "0001-01-01T00:00:00.000Z") date_obj = datetime.max date_str = Serializer.serialize_iso(date_obj) - self.assertEqual(date_str, '9999-12-31T23:59:59.999999Z') + self.assertEqual(date_str, "9999-12-31T23:59:59.999999Z") - date_obj = isodate.parse_datetime('2012-02-24T00:53:52.000001Z') + date_obj = isodate.parse_datetime("2012-02-24T00:53:52.000001Z") date_str = Serializer.serialize_iso(date_obj) - assert date_str == '2012-02-24T00:53:52.000001Z' + assert date_str == "2012-02-24T00:53:52.000001Z" - date_obj = isodate.parse_datetime('2012-02-24T00:53:52.780Z') + date_obj = isodate.parse_datetime("2012-02-24T00:53:52.780Z") date_str = Serializer.serialize_iso(date_obj) - assert date_str == '2012-02-24T00:53:52.780Z' + assert date_str == "2012-02-24T00:53:52.780Z" def test_serialize_time(self): - time_str = Serializer.serialize_time(time(11,22,33)) + time_str = Serializer.serialize_time(time(11, 22, 33)) assert time_str == "11:22:33" - time_str = Serializer.serialize_time(time(11,22,33,444)) + time_str = Serializer.serialize_time(time(11, 22, 33, 444)) assert time_str == "11:22:33.444" def test_serialize_primitive_types(self): - a = self.s.serialize_data(1, 'int') + a = self.s.serialize_data(1, "int") self.assertEqual(a, 1) - b = self.s.serialize_data(True, 'bool') + b = self.s.serialize_data(True, "bool") self.assertEqual(b, True) - c = self.s.serialize_data('True', 'str') - self.assertEqual(c, 'True') + c = self.s.serialize_data("True", "str") + self.assertEqual(c, "True") - d = self.s.serialize_data(100.0123, 'float') + d = self.s.serialize_data(100.0123, "float") self.assertEqual(d, 100.0123) def test_serialize_decimal(self): - result = self.s.serialize_data(decimal.Decimal('0.33333'), 'decimal') + result = self.s.serialize_data(decimal.Decimal("0.33333"), "decimal") self.assertEqual(result, 0.33333) - result = self.s.serialize_data(0.33333, 'decimal') + result = self.s.serialize_data(0.33333, "decimal") self.assertEqual(result, 0.33333) with self.assertRaises(SerializationError): - self.s.serialize_data('not a decimal', 'decimal') + self.s.serialize_data("not a decimal", "decimal") def test_serialize_object(self): - a = self.s.body(1, 'object') + a = self.s.body(1, "object") self.assertEqual(a, 1) - b = self.s.body(True, 'object') + b = self.s.body(True, "object") self.assertEqual(b, True) - c = self.s.serialize_data('True', 'object') - self.assertEqual(c, 'True') + c = self.s.serialize_data("True", "object") + self.assertEqual(c, "True") - d = self.s.serialize_data(100.0123, 'object') + d = self.s.serialize_data(100.0123, "object") self.assertEqual(d, 100.0123) - e = self.s.serialize_data({}, 'object') + e = self.s.serialize_data({}, "object") self.assertEqual(e, {}) - f = self.s.body({"test":"data"}, 'object') - self.assertEqual(f, {"test":"data"}) + f = self.s.body({"test": "data"}, "object") + self.assertEqual(f, {"test": "data"}) - g = self.s.body({"test":{"value":"data"}}, 'object') - self.assertEqual(g, {"test":{"value":"data"}}) + g = self.s.body({"test": {"value": "data"}}, "object") + self.assertEqual(g, {"test": {"value": "data"}}) - h = self.s.serialize_data({"test":self.TestObj('id')}, 'object') - self.assertEqual(h, {"test":{'id': 'id'}}) + h = self.s.serialize_data({"test": self.TestObj("id")}, "object") + self.assertEqual(h, {"test": {"id": "id"}}) - i = self.s.serialize_data({"test":[1,2,3,4,5]}, 'object') - self.assertEqual(i, {"test":[1,2,3,4,5]}) + i = self.s.serialize_data({"test": [1, 2, 3, 4, 5]}, "object") + self.assertEqual(i, {"test": [1, 2, 3, 4, 5]}) def test_serialize_empty_iter(self): - a = self.s.serialize_dict({}, 'int') + a = self.s.serialize_dict({}, "int") self.assertEqual(a, {}) - b = self.s.serialize_iter([], 'int') + b = self.s.serialize_iter([], "int") self.assertEqual(b, []) def test_serialize_str_as_iter(self): with self.assertRaises(SerializationError): - self.s.serialize_iter("I am a string", 'str') + self.s.serialize_iter("I am a string", "str") def test_serialize_int_as_iter_with_div(self): # https://github.com/Azure/azure-sdk-for-python/issues/4501 - assert self.s.serialize_iter([1,2,3,4], "int", ",") == "1,2,3,4" + assert self.s.serialize_iter([1, 2, 3, 4], "int", ",") == "1,2,3,4" def test_serialize_from_dict_datetime(self): class DateTimeTest(Model): _attribute_map = { - 'birthday':{'key':'birthday','type':'iso-8601'}, + "birthday": {"key": "birthday", "type": "iso-8601"}, } + def __init__(self, birthday): self.birthday = birthday - serializer = Serializer({ - 'DateTimeTest': DateTimeTest - }) + serializer = Serializer({"DateTimeTest": DateTimeTest}) - mydate = serializer.body( - {'birthday': datetime(1980, 12, 27)}, - 'DateTimeTest' - ) + mydate = serializer.body({"birthday": datetime(1980, 12, 27)}, "DateTimeTest") assert mydate["birthday"] == "1980-12-27T00:00:00.000Z" def test_serialize_json_obj(self): @@ -960,63 +952,65 @@ def test_serialize_json_obj(self): class ComplexId(Model): _validation = {} - _attribute_map = {'id':{'key':'id','type':'int'}, - 'name':{'key':'name','type':'str'}, - 'age':{'key':'age','type':'float'}, - 'male':{'key':'male','type':'bool'}, - 'birthday':{'key':'birthday','type':'iso-8601'}, - 'anniversary':{'key':'anniversary', 'type':'iso-8601'}} + _attribute_map = { + "id": {"key": "id", "type": "int"}, + "name": {"key": "name", "type": "str"}, + "age": {"key": "age", "type": "float"}, + "male": {"key": "male", "type": "bool"}, + "birthday": {"key": "birthday", "type": "iso-8601"}, + "anniversary": {"key": "anniversary", "type": "iso-8601"}, + } id = 1 name = "Joey" age = 23.36 male = True - birthday = '1992-01-01T00:00:00.000Z' - anniversary = isodate.parse_datetime('2013-12-08T00:00:00') + birthday = "1992-01-01T00:00:00.000Z" + anniversary = isodate.parse_datetime("2013-12-08T00:00:00") class ComplexJson(Model): _validation = {} - _attribute_map = {'p1':{'key':'p1','type':'str'}, - 'p2':{'key':'p2','type':'str'}, - 'top_date':{'key':'top_date', 'type':'iso-8601'}, - 'top_dates':{'key':'top_dates', 'type':'[iso-8601]'}, - 'insider':{'key':'insider','type':'{iso-8601}'}, - 'top_complex':{'key':'top_complex','type':'ComplexId'}} - - p1 = 'value1' - p2 = 'value2' - top_date = isodate.parse_datetime('2014-01-01T00:00:00') - top_dates = [isodate.parse_datetime('1900-01-01T00:00:00'), isodate.parse_datetime('1901-01-01T00:00:00')] + _attribute_map = { + "p1": {"key": "p1", "type": "str"}, + "p2": {"key": "p2", "type": "str"}, + "top_date": {"key": "top_date", "type": "iso-8601"}, + "top_dates": {"key": "top_dates", "type": "[iso-8601]"}, + "insider": {"key": "insider", "type": "{iso-8601}"}, + "top_complex": {"key": "top_complex", "type": "ComplexId"}, + } + + p1 = "value1" + p2 = "value2" + top_date = isodate.parse_datetime("2014-01-01T00:00:00") + top_dates = [isodate.parse_datetime("1900-01-01T00:00:00"), isodate.parse_datetime("1901-01-01T00:00:00")] insider = { - 'k1': isodate.parse_datetime('2015-01-01T00:00:00'), - 'k2': isodate.parse_datetime('2016-01-01T00:00:00'), - 'k3': isodate.parse_datetime('2017-01-01T00:00:00')} + "k1": isodate.parse_datetime("2015-01-01T00:00:00"), + "k2": isodate.parse_datetime("2016-01-01T00:00:00"), + "k3": isodate.parse_datetime("2017-01-01T00:00:00"), + } top_complex = ComplexId() - message =self.s._serialize(ComplexJson()) + message = self.s._serialize(ComplexJson()) output = { - 'p1': 'value1', - 'p2': 'value2', - 'top_date': '2014-01-01T00:00:00.000Z', - 'top_dates': [ - '1900-01-01T00:00:00.000Z', - '1901-01-01T00:00:00.000Z' - ], - 'insider': { - 'k1': '2015-01-01T00:00:00.000Z', - 'k2': '2016-01-01T00:00:00.000Z', - 'k3': '2017-01-01T00:00:00.000Z' + "p1": "value1", + "p2": "value2", + "top_date": "2014-01-01T00:00:00.000Z", + "top_dates": ["1900-01-01T00:00:00.000Z", "1901-01-01T00:00:00.000Z"], + "insider": { + "k1": "2015-01-01T00:00:00.000Z", + "k2": "2016-01-01T00:00:00.000Z", + "k3": "2017-01-01T00:00:00.000Z", + }, + "top_complex": { + "id": 1, + "name": "Joey", + "age": 23.36, + "male": True, + "birthday": "1992-01-01T00:00:00.000Z", + "anniversary": "2013-12-08T00:00:00.000Z", }, - 'top_complex': { - 'id': 1, - 'name': 'Joey', - 'age': 23.36, - 'male': True, - 'birthday': '1992-01-01T00:00:00.000Z', - 'anniversary': '2013-12-08T00:00:00.000Z', - } } self.maxDiff = None self.assertEqual(message, output) @@ -1027,10 +1021,11 @@ class ComplexJson(Model): def test_polymorphic_serialization(self): self.maxDiff = None + class Zoo(Model): _attribute_map = { - "animals":{"key":"Animals", "type":"[Animal]"}, + "animals": {"key": "Animals", "type": "[Animal]"}, } def __init__(self, animals=None): @@ -1038,14 +1033,9 @@ def __init__(self, animals=None): class Animal(Model): - _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "d_type":{"key":"dType", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}, "d_type": {"key": "dType", "type": "str"}} - _subtype_map = { - 'd_type': {"cat":"Cat", "dog":"Dog"} - } + _subtype_map = {"d_type": {"cat": "Cat", "dog": "Dog"}} def __init__(self, name=None): self.name = name @@ -1053,73 +1043,60 @@ def __init__(self, name=None): class Dog(Animal): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_dog_food":{"key":"likesDogFood","type":"bool"}, - "d_type":{"key":"dType", "type":"str"} - } + "name": {"key": "Name", "type": "str"}, + "likes_dog_food": {"key": "likesDogFood", "type": "bool"}, + "d_type": {"key": "dType", "type": "str"}, + } def __init__(self, name=None, likes_dog_food=None): self.likes_dog_food = likes_dog_food super(Dog, self).__init__(name) - self.d_type = 'dog' + self.d_type = "dog" class Cat(Animal): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_mice":{"key":"likesMice","type":"bool"}, - "dislikes":{"key":"dislikes","type":"Animal"}, - "d_type":{"key":"dType", "type":"str"} - } + "name": {"key": "Name", "type": "str"}, + "likes_mice": {"key": "likesMice", "type": "bool"}, + "dislikes": {"key": "dislikes", "type": "Animal"}, + "d_type": {"key": "dType", "type": "str"}, + } - _subtype_map = { - "d_type":{"siamese":"Siamese"} - } + _subtype_map = {"d_type": {"siamese": "Siamese"}} - def __init__(self, name=None, likes_mice=None, dislikes = None): + def __init__(self, name=None, likes_mice=None, dislikes=None): self.likes_mice = likes_mice self.dislikes = dislikes super(Cat, self).__init__(name) - self.d_type = 'cat' + self.d_type = "cat" class Siamese(Cat): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_mice":{"key":"likesMice","type":"bool"}, - "dislikes":{"key":"dislikes","type":"Animal"}, - "color":{"key":"Color", "type":"str"}, - "d_type":{"key":"dType", "type":"str"} - } - - def __init__(self, name=None, likes_mice=None, dislikes = None, color=None): + "name": {"key": "Name", "type": "str"}, + "likes_mice": {"key": "likesMice", "type": "bool"}, + "dislikes": {"key": "dislikes", "type": "Animal"}, + "color": {"key": "Color", "type": "str"}, + "d_type": {"key": "dType", "type": "str"}, + } + + def __init__(self, name=None, likes_mice=None, dislikes=None, color=None): self.color = color super(Siamese, self).__init__(name, likes_mice, dislikes) - self.d_type = 'siamese' + self.d_type = "siamese" message = { "Animals": [ - { - "dType": "dog", - "likesDogFood": True, - "Name": "Fido" - }, - { - "dType": "cat", - "likesMice": False, - "dislikes": { - "dType": "dog", - "likesDogFood": True, - "Name": "Angry" - }, - "Name": "Felix" - }, - { - "dType": "siamese", - "Color": "grey", - "likesMice": True, - "Name": "Finch" - }]} + {"dType": "dog", "likesDogFood": True, "Name": "Fido"}, + { + "dType": "cat", + "likesMice": False, + "dislikes": {"dType": "dog", "likesDogFood": True, "Name": "Angry"}, + "Name": "Felix", + }, + {"dType": "siamese", "Color": "grey", "likesMice": True, "Name": "Finch"}, + ] + } zoo = Zoo() angry = Dog() @@ -1146,35 +1123,23 @@ def __init__(self, name=None, likes_mice=None, dislikes = None, color=None): self.assertEqual(serialized, message) old_dependencies = self.s.dependencies - self.s.dependencies = { - 'Zoo': Zoo, - 'Animal': Animal, - 'Dog': Dog, - 'Cat': Cat, - 'Siamese': Siamese - } + self.s.dependencies = {"Zoo": Zoo, "Animal": Animal, "Dog": Dog, "Cat": Cat, "Siamese": Siamese} - serialized = self.s.body({ - "animals": [{ - "dType": "dog", - "likes_dog_food": True, - "name": "Fido" - },{ - "dType": "cat", - "likes_mice": False, - "dislikes": { - "dType": "dog", - "likes_dog_food": True, - "name": "Angry" - }, - "name": "Felix" - },{ - "dType": "siamese", - "color": "grey", - "likes_mice": True, - "name": "Finch" - }] - }, "Zoo") + serialized = self.s.body( + { + "animals": [ + {"dType": "dog", "likes_dog_food": True, "name": "Fido"}, + { + "dType": "cat", + "likes_mice": False, + "dislikes": {"dType": "dog", "likes_dog_food": True, "name": "Angry"}, + "name": "Felix", + }, + {"dType": "siamese", "color": "grey", "likes_mice": True, "name": "Finch"}, + ] + }, + "Zoo", + ) self.assertEqual(serialized, message) self.s.dependencies = old_dependencies @@ -1185,32 +1150,20 @@ class TestKeyTypeObj(Model): _validation = {} _attribute_map = { - 'attr_a': {'key':'attr_a', 'type':'int'}, - 'attr_b': {'key':'id', 'type':'int'}, - 'attr_c': {'key':'KeyC', 'type': 'int'}, - 'attr_d': {'key':'properties.KeyD', 'type': 'int'}, + "attr_a": {"key": "attr_a", "type": "int"}, + "attr_b": {"key": "id", "type": "int"}, + "attr_c": {"key": "KeyC", "type": "int"}, + "attr_d": {"key": "properties.KeyD", "type": "int"}, } old_dependencies = self.s.dependencies self.s.dependencies = { - 'TestKeyTypeObj': TestKeyTypeObj, + "TestKeyTypeObj": TestKeyTypeObj, } - serialized = self.s.body({ - "attr_a": 1, - "id": 2, - "keyc": 3, - "keyd": 4 - }, "TestKeyTypeObj") + serialized = self.s.body({"attr_a": 1, "id": 2, "keyc": 3, "keyd": 4}, "TestKeyTypeObj") - message = { - "attr_a": 1, - "id": 2, - "KeyC": 3, - "properties": { - "KeyD": 4 - } - } + message = {"attr_a": 1, "id": 2, "KeyC": 3, "properties": {"KeyD": 4}} self.assertEqual(serialized, message) @@ -1220,78 +1173,67 @@ def test_additional_properties_no_send(self): class AdditionalTest(Model): - _attribute_map = { - "name": {"key":"Name", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}} def __init__(self, name=None): self.name = name - o = AdditionalTest( - name='test' - ) - o.additional_properties={ + o = AdditionalTest(name="test") + o.additional_properties = { "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, } - expected_message = { - "Name": "test" - } + expected_message = {"Name": "test"} - s = Serializer({'AdditionalTest': AdditionalTest}) + s = Serializer({"AdditionalTest": AdditionalTest}) - serialized = s.body(o, 'AdditionalTest') + serialized = s.body(o, "AdditionalTest") self.assertEqual(serialized, expected_message) - def test_additional_properties_manual(self): class AdditionalTest(Model): - _attribute_map = { - "name": {"key":"Name", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}} def __init__(self, name=None): self.name = name + AdditionalTest.enable_additional_properties_sending() - o = AdditionalTest( - name='test' - ) - o.additional_properties={ + o = AdditionalTest(name="test") + o.additional_properties = { "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, } expected_message = { "Name": "test", "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, } - s = Serializer({'AdditionalTest': AdditionalTest}) + s = Serializer({"AdditionalTest": AdditionalTest}) - serialized = s.body(o, 'AdditionalTest') + serialized = s.body(o, "AdditionalTest") self.assertEqual(serialized, expected_message) - def test_additional_properties(self): class AdditionalTest(Model): _attribute_map = { - "name": {"key":"Name", "type":"str"}, - 'additional_properties': {'key': '', 'type': '{object}'} + "name": {"key": "Name", "type": "str"}, + "additional_properties": {"key": "", "type": "{object}"}, } def __init__(self, name=None, additional_properties=None): @@ -1299,53 +1241,49 @@ def __init__(self, name=None, additional_properties=None): self.additional_properties = additional_properties o = AdditionalTest( - name='test', + name="test", additional_properties={ "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} - } + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, + }, ) expected_message = { "Name": "test", "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, } - s = Serializer({'AdditionalTest': AdditionalTest}) + s = Serializer({"AdditionalTest": AdditionalTest}) - serialized = s.body(o, 'AdditionalTest') + serialized = s.body(o, "AdditionalTest") self.assertEqual(serialized, expected_message) - def test_additional_properties_with_auto_model(self): class AdditionalTest(Model): _attribute_map = { - "name": {"key":"Name", "type":"str"}, - "display_name": {"key":"DisplayName", "type":"str"}, - 'additional_properties': {'key': '', 'type': '{object}'} + "name": {"key": "Name", "type": "str"}, + "display_name": {"key": "DisplayName", "type": "str"}, + "additional_properties": {"key": "", "type": "{object}"}, } - o = { - 'name': 'test', - 'display_name': "display_name" - } + o = {"name": "test", "display_name": "display_name"} expected_message = { "Name": "test", "DisplayName": "display_name", } - s = Serializer({'AdditionalTest': AdditionalTest}) + s = Serializer({"AdditionalTest": AdditionalTest}) - serialized = s.body(o, 'AdditionalTest') + serialized = s.body(o, "AdditionalTest") self.assertEqual(serialized, expected_message) @@ -1354,8 +1292,8 @@ def test_additional_properties_declared(self): class AdditionalTest(Model): _attribute_map = { - "name": {"key":"Name", "type":"str"}, - 'additional_properties': {'key': 'AddProp', 'type': '{object}'} + "name": {"key": "Name", "type": "str"}, + "additional_properties": {"key": "AddProp", "type": "{object}"}, } def __init__(self, name=None, additional_properties=None): @@ -1363,49 +1301,40 @@ def __init__(self, name=None, additional_properties=None): self.additional_properties = additional_properties o = AdditionalTest( - name='test', + name="test", additional_properties={ "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} - } + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, + }, ) expected_message = { "Name": "test", - "AddProp": { - "PropInt": 2, - "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} - } + "AddProp": {"PropInt": 2, "PropStr": "AdditionalProperty", "PropArray": [1, 2, 3], "PropDict": {"a": "b"}}, } - s = Serializer({'AdditionalTest': AdditionalTest}) + s = Serializer({"AdditionalTest": AdditionalTest}) - serialized = s.body(o, 'AdditionalTest') + serialized = s.body(o, "AdditionalTest") self.assertEqual(serialized, expected_message) # Make it declared as a property AND readonly - AdditionalTest._validation = { - 'additional_properties': {'readonly': True} - } + AdditionalTest._validation = {"additional_properties": {"readonly": True}} - expected_message = { - "Name": "test" - } + expected_message = {"Name": "test"} - s = Serializer({'AdditionalTest': AdditionalTest}) + s = Serializer({"AdditionalTest": AdditionalTest}) - serialized = s.body(o, 'AdditionalTest') + serialized = s.body(o, "AdditionalTest") self.assertEqual(serialized, expected_message) def test_long_as_type_object(self): """Test irrelevant on Python 3. But still doing it to test regression. - https://github.com/Azure/msrest-for-python/pull/121 + https://github.com/Azure/msrest-for-python/pull/121 """ try: @@ -1414,81 +1343,75 @@ def test_long_as_type_object(self): long_type = int s = Serializer() - assert s.serialize_data(long_type(1), 'object') == long_type(1) + assert s.serialize_data(long_type(1), "object") == long_type(1) class TestModel(Model): - _attribute_map = {'data': {'key': 'data', 'type': 'object'}} + _attribute_map = {"data": {"key": "data", "type": "object"}} - m = TestModel(data = {'id': long_type(1)}) + m = TestModel(data={"id": long_type(1)}) serialized = m.serialize() - assert serialized == { - 'data': {'id': long_type(1)} - } + assert serialized == {"data": {"id": long_type(1)}} def test_unicode_as_type_object(self): """Test irrelevant on Python 3. But still doing it to test regression. - https://github.com/Azure/msrest-for-python/issue/221 + https://github.com/Azure/msrest-for-python/issue/221 """ s = Serializer() - assert s.serialize_data(u"\ua015", 'object') == u"\ua015" + assert s.serialize_data("\ua015", "object") == "\ua015" class TestModel(Model): - _attribute_map = {'data': {'key': 'data', 'type': 'object'}} + _attribute_map = {"data": {"key": "data", "type": "object"}} - m = TestModel(data = {'id': u"\ua015"}) + m = TestModel(data={"id": "\ua015"}) serialized = m.serialize() - assert serialized == { - 'data': {'id': u"\ua015"} - } + assert serialized == {"data": {"id": "\ua015"}} def test_datetime_types_as_type_object(self): - """https://github.com/Azure/msrest-for-python/issues/223 - """ + """https://github.com/Azure/msrest-for-python/issues/223""" class TestModel(Model): - _attribute_map = {'data': {'key': 'data', 'type': 'object'}} - - m = TestModel(data = { - 'datetime': isodate.parse_datetime('2012-02-24T00:53:52.780Z'), - 'date': date(2019,5,1), - 'time': time(11,12,13), - 'timedelta': timedelta(56) - }) + _attribute_map = {"data": {"key": "data", "type": "object"}} + + m = TestModel( + data={ + "datetime": isodate.parse_datetime("2012-02-24T00:53:52.780Z"), + "date": date(2019, 5, 1), + "time": time(11, 12, 13), + "timedelta": timedelta(56), + } + ) serialized = m.serialize() - assert serialized['data'] == { - 'datetime': '2012-02-24T00:53:52.780Z', - 'date': '2019-05-01', - 'time': '11:12:13', - 'timedelta': 'P56D' + assert serialized["data"] == { + "datetime": "2012-02-24T00:53:52.780Z", + "date": "2019-05-01", + "time": "11:12:13", + "timedelta": "P56D", } def test_decimal_types_as_type_object(self): - """https://github.com/Azure/msrest-for-python/issues/223 - """ + """https://github.com/Azure/msrest-for-python/issues/223""" class TestModel(Model): - _attribute_map = {'data': {'key': 'data', 'type': 'object'}} + _attribute_map = {"data": {"key": "data", "type": "object"}} - m = TestModel(data = { - 'decimal': Decimal('1.1'), - }) + m = TestModel( + data={ + "decimal": Decimal("1.1"), + } + ) serialized = m.serialize() - assert serialized['data'] == { - 'decimal': 1.1 - } + assert serialized["data"] == {"decimal": 1.1} def test_json_with_xml_map(self): - basic_json = {'age': 37, 'country': 'france'} + basic_json = {"age": 37, "country": "france"} class XmlModel(Model): _attribute_map = { - 'age': {'key': 'age', 'type': 'int', 'xml':{'name': 'Age'}}, - 'country': {'key': 'country', 'type': 'str', 'xml':{'name': 'country', 'attr': True}}, - } - _xml_map = { - 'name': 'Data' + "age": {"key": "age", "type": "int", "xml": {"name": "Age"}}, + "country": {"key": "country", "type": "str", "xml": {"name": "country", "attr": True}}, } + _xml_map = {"name": "Data"} mymodel = XmlModel( age=37, @@ -1496,9 +1419,10 @@ class XmlModel(Model): ) s = Serializer({"XmlModel": XmlModel}) - rawxml = s.body(mymodel, 'XmlModel', is_xml=False) + rawxml = s.body(mymodel, "XmlModel", is_xml=False) + + assert rawxml == basic_json - assert rawxml==basic_json class TestRuntimeDeserialized(unittest.TestCase): @@ -1506,23 +1430,20 @@ class TestObj(Model): _validation = {} _attribute_map = { - 'attr_a': {'key':'id', 'type':'str'}, - 'attr_b': {'key':'AttrB', 'type':'int'}, - 'attr_c': {'key':'Key_C', 'type': 'bool'}, - 'attr_d': {'key':'AttrD', 'type':'[int]'}, - 'attr_e': {'key':'AttrE', 'type': '{float}'}, - 'attr_f': {'key':'AttrF', 'type': '[[str]]'} - } + "attr_a": {"key": "id", "type": "str"}, + "attr_b": {"key": "AttrB", "type": "int"}, + "attr_c": {"key": "Key_C", "type": "bool"}, + "attr_d": {"key": "AttrD", "type": "[int]"}, + "attr_e": {"key": "AttrE", "type": "{float}"}, + "attr_f": {"key": "AttrF", "type": "[[str]]"}, + } _header_map = { - 'client_request_id': {'key': 'client-request-id', 'type':'str'}, - 'e_tag': {'key': 'etag', 'type':'str'}, - } - - _response_map = { - 'status_code': {'key':'status_code', 'type':'str'} - } + "client_request_id": {"key": "client-request-id", "type": "str"}, + "e_tag": {"key": "etag", "type": "str"}, + } + _response_map = {"status_code": {"key": "status_code", "type": "str"}} def setUp(self): self.d = Deserializer() @@ -1530,33 +1451,33 @@ def setUp(self): def test_cls_method_deserialization(self): json_data = { - 'id': 'myid', - 'AttrB': 42, - 'Key_C': True, - 'AttrD': [1,2,3], - 'AttrE': {'pi': 3.14}, - 'AttrF': [['internal', 'list', 'of', 'strings']] + "id": "myid", + "AttrB": 42, + "Key_C": True, + "AttrD": [1, 2, 3], + "AttrE": {"pi": 3.14}, + "AttrF": [["internal", "list", "of", "strings"]], } def assert_model(inst): - self.assertEqual(inst.attr_a, 'myid') + self.assertEqual(inst.attr_a, "myid") self.assertEqual(inst.attr_b, 42) self.assertEqual(inst.attr_c, True) - self.assertEqual(inst.attr_d, [1,2,3]) - self.assertEqual(inst.attr_e, {'pi': 3.14}) - self.assertEqual(inst.attr_f, [['internal', 'list', 'of', 'strings']]) + self.assertEqual(inst.attr_d, [1, 2, 3]) + self.assertEqual(inst.attr_e, {"pi": 3.14}) + self.assertEqual(inst.attr_f, [["internal", "list", "of", "strings"]]) model_instance = self.TestObj.from_dict(json_data) assert_model(model_instance) # Get an attribute version of this model attr_data = { - 'attr_a': 'myid', - 'attr_b': 42, - 'attr_c': True, - 'attr_d': [1,2,3], - 'attr_e': {'pi': 3.14}, - 'attr_f': [['internal', 'list', 'of', 'strings']] + "attr_a": "myid", + "attr_b": 42, + "attr_c": True, + "attr_d": [1, 2, 3], + "attr_e": {"pi": 3.14}, + "attr_f": [["internal", "list", "of", "strings"]], } self.TestObj.from_dict(attr_data) assert_model(model_instance) @@ -1569,19 +1490,15 @@ def test_twice_key_scenario(self): class LocalModel(Model): _attribute_map = { - 'id': {'key': 'id', 'type': 'int'}, - 'type': {'key': 'type_dont_matter_not_used', 'type': 'str'}, - 'type2': {'key': 'properties.type', 'type': 'str'}, + "id": {"key": "id", "type": "int"}, + "type": {"key": "type_dont_matter_not_used", "type": "str"}, + "type2": {"key": "properties.type", "type": "str"}, } def __init__(self, **kwargs): super(LocalModel, self).__init__(**kwargs) - raw = { - 'id': 42, - 'type': "type", - 'type2': "type2" - } + raw = {"id": 42, "type": "type", "type2": "type2"} m = LocalModel.from_dict(raw) assert m.id == 42 @@ -1589,66 +1506,48 @@ def __init__(self, **kwargs): assert m.type2 == "type2" def test_array_deserialize(self): - result = self.d('[str]', ["a","b"]) - assert result == ['a','b'] + result = self.d("[str]", ["a", "b"]) + assert result == ["a", "b"] def test_personalize_deserialization(self): class TestDurationObj(Model): _attribute_map = { - 'attr_a': {'key':'attr_a', 'type':'duration'}, + "attr_a": {"key": "attr_a", "type": "duration"}, } with self.assertRaises(DeserializationError): - obj = TestDurationObj.from_dict({ - "attr_a": "00:00:10" - }) + obj = TestDurationObj.from_dict({"attr_a": "00:00:10"}) def duration_rest_key_extractor(attr, attr_desc, data): value = rest_key_extractor(attr, attr_desc, data) if attr == "attr_a": # Stupid parsing, this is just a test - return "PT"+value[-2:]+"S" + return "PT" + value[-2:] + "S" - obj = TestDurationObj.from_dict( - {"attr_a": "00:00:10"}, - key_extractors=[duration_rest_key_extractor] - ) + obj = TestDurationObj.from_dict({"attr_a": "00:00:10"}, key_extractors=[duration_rest_key_extractor]) self.assertEqual(timedelta(seconds=10), obj.attr_a) - def test_robust_deserialization(self): class TestKeyTypeObj(Model): _validation = {} _attribute_map = { - 'attr_a': {'key':'attr_a', 'type':'int'}, - 'attr_b': {'key':'id', 'type':'int'}, - 'attr_c': {'key':'KeyC', 'type': 'int'}, - 'attr_d': {'key':'properties.KeyD', 'type': 'int'}, + "attr_a": {"key": "attr_a", "type": "int"}, + "attr_b": {"key": "id", "type": "int"}, + "attr_c": {"key": "KeyC", "type": "int"}, + "attr_d": {"key": "properties.KeyD", "type": "int"}, } - obj = TestKeyTypeObj.from_dict({ - "attr_a": 1, - "id": 2, - "keyc": 3, - "keyd": 4 - }) + obj = TestKeyTypeObj.from_dict({"attr_a": 1, "id": 2, "keyc": 3, "keyd": 4}) self.assertEqual(1, obj.attr_a) self.assertEqual(2, obj.attr_b) self.assertEqual(3, obj.attr_c) self.assertEqual(4, obj.attr_d) - obj = TestKeyTypeObj.from_dict({ - "attr_a": 1, - "id": 2, - "keyc": 3, - "properties": { - "KeyD": 4 - } - }) + obj = TestKeyTypeObj.from_dict({"attr_a": 1, "id": 2, "keyc": 3, "properties": {"KeyD": 4}}) self.assertEqual(1, obj.attr_a) self.assertEqual(2, obj.attr_b) @@ -1658,13 +1557,9 @@ class TestKeyTypeObj(Model): # This one used to raise an exception, but after https://github.com/Azure/msrest-for-python/pull/204 # we decide to accept it with log warning - obj = TestKeyTypeObj.from_dict({ - "attr_a": 1, - "attr_b": 12, # Conflict with "id" - "id": 14, # Conflict with "attr_b" - "keyc": 3, - "keyd": 4 - }) + obj = TestKeyTypeObj.from_dict( + {"attr_a": 1, "attr_b": 12, "id": 14, "keyc": 3, "keyd": 4} # Conflict with "id" # Conflict with "attr_b" + ) self.assertEqual(1, obj.attr_a) self.assertEqual(12, obj.attr_b) # from_dict will prioritize attribute syntax @@ -1675,31 +1570,27 @@ def test_basic_deserialization(self): class TestObj(Model): _validation = { - 'name': {'min_length': 3}, + "name": {"min_length": 3}, } _attribute_map = { - 'name': {'key':'RestName', 'type':'str'}, + "name": {"key": "RestName", "type": "str"}, } def __init__(self, name): self.name = name - obj = TestObj.from_dict({'name': 'ab'}) - self.assertEqual('ab', obj.name) + obj = TestObj.from_dict({"name": "ab"}) + self.assertEqual("ab", obj.name) def test_deserialize_flattening(self): # https://github.com/Azure/msrest-for-python/issues/197 - json_body = { - "properties" : { - "properties": None - } - } + json_body = {"properties": {"properties": None}} class ComputeResource(Model): _attribute_map = { - 'properties': {'key': 'properties', 'type': 'VirtualMachine'}, + "properties": {"key": "properties", "type": "VirtualMachine"}, } def __init__(self, properties=None, **kwargs): @@ -1708,121 +1599,123 @@ def __init__(self, properties=None, **kwargs): class VirtualMachine(Model): _attribute_map = { - 'virtual_machine_size': {'key': 'properties.virtualMachineSize', 'type': 'str'}, - 'ssh_port': {'key': 'properties.sshPort', 'type': 'int'}, - 'address': {'key': 'properties.address', 'type': 'str'}, - 'administrator_account': {'key': 'properties.administratorAccount', 'type': 'VirtualMachineSshCredentials'}, + "virtual_machine_size": {"key": "properties.virtualMachineSize", "type": "str"}, + "ssh_port": {"key": "properties.sshPort", "type": "int"}, + "address": {"key": "properties.address", "type": "str"}, + "administrator_account": { + "key": "properties.administratorAccount", + "type": "VirtualMachineSshCredentials", + }, } def __init__(self, **kwargs): super(VirtualMachine, self).__init__(**kwargs) - self.virtual_machine_size = kwargs.get('virtual_machine_size', None) - self.ssh_port = kwargs.get('ssh_port', None) - self.address = kwargs.get('address', None) - self.administrator_account = kwargs.get('administrator_account', None) + self.virtual_machine_size = kwargs.get("virtual_machine_size", None) + self.ssh_port = kwargs.get("ssh_port", None) + self.address = kwargs.get("address", None) + self.administrator_account = kwargs.get("administrator_account", None) - d = Deserializer({ - 'ComputeResource': ComputeResource, - 'VirtualMachine': VirtualMachine, - }) - response = d(ComputeResource, json.dumps(json_body), 'application/json') + d = Deserializer( + { + "ComputeResource": ComputeResource, + "VirtualMachine": VirtualMachine, + } + ) + response = d(ComputeResource, json.dumps(json_body), "application/json") def test_deserialize_storage(self): StorageAccount = storage_models.StorageAccount json_storage = { - 'id': '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test_mgmt_storage_test_storage_accounts43b8102a/providers/Microsoft.Storage/storageAccounts/pyarmstorage43b8102a', - 'kind': 'Storage', - 'location': 'westus', - 'name': 'pyarmstorage43b8102a', - 'properties': { - 'creationTime': '2017-07-19T23:19:21.7640412Z', - 'primaryEndpoints': {'blob': 'https://pyarmstorage43b8102a.blob.core.windows.net/', - 'file': 'https://pyarmstorage43b8102a.file.core.windows.net/', - 'queue': 'https://pyarmstorage43b8102a.queue.core.windows.net/', - 'table': 'https://pyarmstorage43b8102a.table.core.windows.net/'}, - 'primaryLocation': 'westus', - 'provisioningState': 'Succeeded', - 'statusOfPrimary': 'available', - 'supportsHttpsTrafficOnly': False}, - 'sku': {'name': 'Standard_LRS', 'tier': 'Standard'}, - 'tags': {}, - 'type': 'Microsoft.Storage/storageAccounts'} + "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test_mgmt_storage_test_storage_accounts43b8102a/providers/Microsoft.Storage/storageAccounts/pyarmstorage43b8102a", + "kind": "Storage", + "location": "westus", + "name": "pyarmstorage43b8102a", + "properties": { + "creationTime": "2017-07-19T23:19:21.7640412Z", + "primaryEndpoints": { + "blob": "https://pyarmstorage43b8102a.blob.core.windows.net/", + "file": "https://pyarmstorage43b8102a.file.core.windows.net/", + "queue": "https://pyarmstorage43b8102a.queue.core.windows.net/", + "table": "https://pyarmstorage43b8102a.table.core.windows.net/", + }, + "primaryLocation": "westus", + "provisioningState": "Succeeded", + "statusOfPrimary": "available", + "supportsHttpsTrafficOnly": False, + }, + "sku": {"name": "Standard_LRS", "tier": "Standard"}, + "tags": {}, + "type": "Microsoft.Storage/storageAccounts", + } storage_account = StorageAccount.deserialize(json_storage) - self.assertEqual(storage_account.id, json_storage['id']) # basic - self.assertEqual(storage_account.sku.name, storage_models.SkuName(json_storage['sku']['name'])) # Nested + enum - self.assertEqual(storage_account.primary_location, json_storage['properties']['primaryLocation']) # Flatten + self.assertEqual(storage_account.id, json_storage["id"]) # basic + self.assertEqual(storage_account.sku.name, storage_models.SkuName(json_storage["sku"]["name"])) # Nested + enum + self.assertEqual(storage_account.primary_location, json_storage["properties"]["primaryLocation"]) # Flatten json_storage_output = storage_account.serialize() - self.assertEqual(len(json_storage_output), 3) # Only 3 keys are not readonly + self.assertEqual(len(json_storage_output), 3) # Only 3 keys are not readonly json_storage_output = storage_account.as_dict(key_transformer=full_restapi_key_transformer) - self.assertListEqual( - sorted(list(json_storage_output.keys())), - sorted(list(json_storage.keys())) - ) + self.assertListEqual(sorted(list(json_storage_output.keys())), sorted(list(json_storage.keys()))) json_storage_output = storage_account.as_dict(keep_readonly=False, key_transformer=full_restapi_key_transformer) - self.assertListEqual( - sorted(list(json_storage_output.keys())), - ['location', 'properties', 'tags'] - ) + self.assertListEqual(sorted(list(json_storage_output.keys())), ["location", "properties", "tags"]) def test_invalid_json(self): """ Test invalid JSON """ with self.assertRaises(DeserializationError): - self.d("[str]", '["tata"]]', 'application/json') - + self.d("[str]", '["tata"]]', "application/json") def test_non_obj_deserialization(self): """ Test direct deserialization of simple types. """ with self.assertRaises(DeserializationError): - self.d("[str]", '', 'application/json') + self.d("[str]", "", "application/json") with self.assertRaises(DeserializationError): - self.d("[str]", json.dumps(''), 'application/json') + self.d("[str]", json.dumps(""), "application/json") with self.assertRaises(DeserializationError): - self.d("[str]", json.dumps({}), 'application/json') + self.d("[str]", json.dumps({}), "application/json") - message = ["a","b","b"] - response = self.d("[str]", json.dumps(message), 'application/json') + message = ["a", "b", "b"] + response = self.d("[str]", json.dumps(message), "application/json") self.assertEqual(response, message) with self.assertRaises(DeserializationError): - self.d("[str]", json.dumps(12345), 'application/json') + self.d("[str]", json.dumps(12345), "application/json") - response = self.d('bool', json.dumps('true'), 'application/json') + response = self.d("bool", json.dumps("true"), "application/json") self.assertEqual(response, True) - response = self.d('bool', json.dumps(1), 'application/json') + response = self.d("bool", json.dumps(1), "application/json") self.assertEqual(response, True) with self.assertRaises(DeserializationError): - self.d('bool', json.dumps("true1"), 'application/json') - + self.d("bool", json.dumps("true1"), "application/json") def test_obj_with_no_attr(self): """ Test deserializing an object with no attributes. """ + class EmptyResponse(Model): _attribute_map = {} _header_map = {} - - deserialized = self.d(EmptyResponse, json.dumps({"a":"b"}), 'application/json') + deserialized = self.d(EmptyResponse, json.dumps({"a": "b"}), "application/json") self.assertIsInstance(deserialized, EmptyResponse) def test_obj_with_malformed_map(self): """ Test deserializing an object with a malformed attributes_map. """ + class BadResponse(Model): _attribute_map = None @@ -1830,107 +1723,107 @@ def __init__(*args, **kwargs): pass with self.assertRaises(DeserializationError): - self.d(BadResponse, json.dumps({"a":"b"}), 'application/json') + self.d(BadResponse, json.dumps({"a": "b"}), "application/json") class BadResponse(Model): - _attribute_map = {"attr":"val"} + _attribute_map = {"attr": "val"} def __init__(*args, **kwargs): pass with self.assertRaises(DeserializationError): - self.d(BadResponse, json.dumps({"a":"b"}), 'application/json') + self.d(BadResponse, json.dumps({"a": "b"}), "application/json") class BadResponse(Model): - _attribute_map = {"attr":{"val":1}} + _attribute_map = {"attr": {"val": 1}} def __init__(*args, **kwargs): pass with self.assertRaises(DeserializationError): - self.d(BadResponse, json.dumps({"a":"b"}), 'application/json') + self.d(BadResponse, json.dumps({"a": "b"}), "application/json") def test_attr_none(self): """ Test serializing an object with None attributes. """ - response = self.d(self.TestObj, 'null', 'application/json') + response = self.d(self.TestObj, "null", "application/json") self.assertIsNone(response) def test_attr_int(self): """ Test deserializing an object with Int attributes. """ - message = {'AttrB':'1234'} - response = self.d(self.TestObj, json.dumps(message), 'application/json') - self.assertTrue(hasattr(response, 'attr_b')) - self.assertEqual(response.attr_b, int(message['AttrB'])) + message = {"AttrB": "1234"} + response = self.d(self.TestObj, json.dumps(message), "application/json") + self.assertTrue(hasattr(response, "attr_b")) + self.assertEqual(response.attr_b, int(message["AttrB"])) with self.assertRaises(DeserializationError): - response = self.d(self.TestObj, json.dumps({'AttrB':'NotANumber'}), 'application/json') + response = self.d(self.TestObj, json.dumps({"AttrB": "NotANumber"}), "application/json") def test_attr_str(self): """ Test deserializing an object with Str attributes. """ - message = {'id':'InterestingValue'} + message = {"id": "InterestingValue"} - response = self.d(self.TestObj, json.dumps(message), 'application/json') - self.assertTrue(hasattr(response, 'attr_a')) - self.assertEqual(response.attr_a, message['id']) + response = self.d(self.TestObj, json.dumps(message), "application/json") + self.assertTrue(hasattr(response, "attr_a")) + self.assertEqual(response.attr_a, message["id"]) - message = {'id':1234} - response = self.d(self.TestObj, json.dumps(message), 'application/json') - self.assertEqual(response.attr_a, str(message['id'])) + message = {"id": 1234} + response = self.d(self.TestObj, json.dumps(message), "application/json") + self.assertEqual(response.attr_a, str(message["id"])) - message = {'id':list()} - response = self.d(self.TestObj, json.dumps(message), 'application/json') - self.assertEqual(response.attr_a, str(message['id'])) + message = {"id": list()} + response = self.d(self.TestObj, json.dumps(message), "application/json") + self.assertEqual(response.attr_a, str(message["id"])) - response = self.d(self.TestObj, json.dumps({'id':None}), 'application/json') + response = self.d(self.TestObj, json.dumps({"id": None}), "application/json") self.assertEqual(response.attr_a, None) def test_attr_bool(self): """ Test deserializing an object with bool attributes. """ - response = self.d(self.TestObj, json.dumps({'Key_C':True}), 'application/json') - self.assertTrue(hasattr(response, 'attr_c')) + response = self.d(self.TestObj, json.dumps({"Key_C": True}), "application/json") + self.assertTrue(hasattr(response, "attr_c")) self.assertEqual(response.attr_c, True) with self.assertRaises(DeserializationError): - response = self.d(self.TestObj, json.dumps({'Key_C':[]}), 'application/json') + response = self.d(self.TestObj, json.dumps({"Key_C": []}), "application/json") - response = self.d(self.TestObj, json.dumps({'Key_C':0}), 'application/json') + response = self.d(self.TestObj, json.dumps({"Key_C": 0}), "application/json") self.assertEqual(response.attr_c, False) with self.assertRaises(DeserializationError): - response = self.d(self.TestObj, json.dumps({'Key_C':"value"}), 'application/json') + response = self.d(self.TestObj, json.dumps({"Key_C": "value"}), "application/json") def test_attr_list_simple(self): """ Test deserializing an object with simple-typed list attributes """ - response = self.d(self.TestObj, json.dumps({'AttrD': []}), 'application/json') + response = self.d(self.TestObj, json.dumps({"AttrD": []}), "application/json") deserialized_list = [d for d in response.attr_d] self.assertEqual(deserialized_list, []) - message = {'AttrD': [1,2,3]} - response = self.d(self.TestObj, json.dumps(message), 'application/json') + message = {"AttrD": [1, 2, 3]} + response = self.d(self.TestObj, json.dumps(message), "application/json") deserialized_list = [d for d in response.attr_d] - self.assertEqual(deserialized_list, message['AttrD']) + self.assertEqual(deserialized_list, message["AttrD"]) - message = {'AttrD': ["1","2","3"]} - response = self.d(self.TestObj, json.dumps(message), 'application/json') + message = {"AttrD": ["1", "2", "3"]} + response = self.d(self.TestObj, json.dumps(message), "application/json") deserialized_list = [d for d in response.attr_d] - self.assertEqual(deserialized_list, [int(i) for i in message['AttrD']]) + self.assertEqual(deserialized_list, [int(i) for i in message["AttrD"]]) with self.assertRaises(DeserializationError): - response = self.d(self.TestObj, json.dumps({'AttrD': ["test","test2","test3"]}), 'application/json') + response = self.d(self.TestObj, json.dumps({"AttrD": ["test", "test2", "test3"]}), "application/json") deserialized_list = [d for d in response.attr_d] with self.assertRaises(DeserializationError): - response = self.d(self.TestObj, json.dumps({'AttrD': "NotAList"}), 'application/json') + response = self.d(self.TestObj, json.dumps({"AttrD": "NotAList"}), "application/json") deserialized_list = [d for d in response.attr_d] self.assertListEqual(sorted(self.d("[str]", ["a", "b", "c"])), ["a", "b", "c"]) @@ -1940,45 +1833,45 @@ def test_attr_list_in_list(self): """ Test deserializing a list of lists """ - response = self.d(self.TestObj, json.dumps({'AttrF':[]}), 'application/json') - self.assertTrue(hasattr(response, 'attr_f')) + response = self.d(self.TestObj, json.dumps({"AttrF": []}), "application/json") + self.assertTrue(hasattr(response, "attr_f")) self.assertEqual(response.attr_f, []) - response = self.d(self.TestObj, json.dumps({'AttrF':None}), 'application/json') - self.assertTrue(hasattr(response, 'attr_f')) + response = self.d(self.TestObj, json.dumps({"AttrF": None}), "application/json") + self.assertTrue(hasattr(response, "attr_f")) self.assertEqual(response.attr_f, None) - response = self.d(self.TestObj, json.dumps({}), 'application/json') - self.assertTrue(hasattr(response, 'attr_f')) + response = self.d(self.TestObj, json.dumps({}), "application/json") + self.assertTrue(hasattr(response, "attr_f")) self.assertEqual(response.attr_f, None) - message = {'AttrF':[[]]} - response = self.d(self.TestObj, json.dumps(message), 'application/json') - self.assertTrue(hasattr(response, 'attr_f')) - self.assertEqual(response.attr_f, message['AttrF']) + message = {"AttrF": [[]]} + response = self.d(self.TestObj, json.dumps(message), "application/json") + self.assertTrue(hasattr(response, "attr_f")) + self.assertEqual(response.attr_f, message["AttrF"]) - message = {'AttrF':[[1,2,3], ['a','b','c']]} - response = self.d(self.TestObj, json.dumps(message), 'application/json') - self.assertTrue(hasattr(response, 'attr_f')) - self.assertEqual(response.attr_f, [[str(i) for i in k] for k in message['AttrF']]) + message = {"AttrF": [[1, 2, 3], ["a", "b", "c"]]} + response = self.d(self.TestObj, json.dumps(message), "application/json") + self.assertTrue(hasattr(response, "attr_f")) + self.assertEqual(response.attr_f, [[str(i) for i in k] for k in message["AttrF"]]) with self.assertRaises(DeserializationError): - response = self.d(self.TestObj, json.dumps({'AttrF':[1,2,3]}), 'application/json') + response = self.d(self.TestObj, json.dumps({"AttrF": [1, 2, 3]}), "application/json") def test_attr_list_complex(self): """ Test deserializing an object with a list of complex objects as an attribute. """ + class ListObj(Model): - _attribute_map = {"abc":{"key":"ABC", "type":"int"}} + _attribute_map = {"abc": {"key": "ABC", "type": "int"}} class CmplxTestObj(Model): _response_map = {} - _attribute_map = {'attr_a': {'key':'id', 'type':'[ListObj]'}} + _attribute_map = {"attr_a": {"key": "id", "type": "[ListObj]"}} - - d = Deserializer({'ListObj':ListObj}) - response = d(CmplxTestObj, json.dumps({"id":[{"ABC": "123"}]}), 'application/json') + d = Deserializer({"ListObj": ListObj}) + response = d(CmplxTestObj, json.dumps({"id": [{"ABC": "123"}]}), "application/json") deserialized_list = list(response.attr_a) self.assertIsInstance(deserialized_list[0], ListObj) @@ -1986,51 +1879,51 @@ class CmplxTestObj(Model): def test_deserialize_object(self): - a = self.d('object', 1) + a = self.d("object", 1) self.assertEqual(a, 1) - b = self.d('object', True) + b = self.d("object", True) self.assertEqual(b, True) - c = self.d('object', 'True') - self.assertEqual(c, 'True') + c = self.d("object", "True") + self.assertEqual(c, "True") - d = self.d('object', 100.0123) + d = self.d("object", 100.0123) self.assertEqual(d, 100.0123) - e = self.d('object', {}) + e = self.d("object", {}) self.assertEqual(e, {}) - f = self.d('object', {"test":"data"}) - self.assertEqual(f, {"test":"data"}) + f = self.d("object", {"test": "data"}) + self.assertEqual(f, {"test": "data"}) - g = self.d('object', {"test":{"value":"data"}}) - self.assertEqual(g, {"test":{"value":"data"}}) + g = self.d("object", {"test": {"value": "data"}}) + self.assertEqual(g, {"test": {"value": "data"}}) with self.assertRaises(DeserializationError): - self.d('object', {"test":self.TestObj()}) + self.d("object", {"test": self.TestObj()}) - h = self.d('object', {"test":[1,2,3,4,5]}) - self.assertEqual(h, {"test":[1,2,3,4,5]}) + h = self.d("object", {"test": [1, 2, 3, 4, 5]}) + self.assertEqual(h, {"test": [1, 2, 3, 4, 5]}) def test_deserialize_date(self): # https://github.com/OAI/OpenAPI-Specification/blob/4d5a749c365682e6718f5a78f113a64391911647/versions/2.0.md#data-types - a = Deserializer.deserialize_date('2018-12-27') - self.assertEqual(date(2018,12,27), a) + a = Deserializer.deserialize_date("2018-12-27") + self.assertEqual(date(2018, 12, 27), a) with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_date('201O-18-90') + a = Deserializer.deserialize_date("201O-18-90") def test_deserialize_time(self): - a = Deserializer.deserialize_time('11:22:33') - assert time(11,22,33) == a + a = Deserializer.deserialize_time("11:22:33") + assert time(11, 22, 33) == a with self.assertRaises(DeserializationError): - Deserializer.deserialize_time('1O:22:33') + Deserializer.deserialize_time("1O:22:33") def test_deserialize_datetime(self): - a = Deserializer.deserialize_iso('9999-12-31T23:59:59+23:59') + a = Deserializer.deserialize_iso("9999-12-31T23:59:59+23:59") utc = a.utctimetuple() self.assertEqual(utc.tm_year, 9999) @@ -2042,9 +1935,9 @@ def test_deserialize_datetime(self): self.assertEqual(a.microsecond, 0) with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('9999-12-31T23:59:59-23:59') + a = Deserializer.deserialize_iso("9999-12-31T23:59:59-23:59") - a = Deserializer.deserialize_iso('1999-12-31T23:59:59-23:59') + a = Deserializer.deserialize_iso("1999-12-31T23:59:59-23:59") utc = a.utctimetuple() self.assertEqual(utc.tm_year, 2000) self.assertEqual(utc.tm_mon, 1) @@ -2054,7 +1947,7 @@ def test_deserialize_datetime(self): self.assertEqual(utc.tm_sec, 59) self.assertEqual(a.microsecond, 0) - a = Deserializer.deserialize_iso('0001-01-01T23:59:00+23:59') + a = Deserializer.deserialize_iso("0001-01-01T23:59:00+23:59") utc = a.utctimetuple() self.assertEqual(utc.tm_year, 1) @@ -2066,7 +1959,7 @@ def test_deserialize_datetime(self): self.assertEqual(a.microsecond, 0) # Only supports microsecond precision up to 6 digits, and chop off the rest - a = Deserializer.deserialize_iso('2018-01-20T18:35:24.666666312345Z') + a = Deserializer.deserialize_iso("2018-01-20T18:35:24.666666312345Z") utc = a.utctimetuple() self.assertEqual(utc.tm_year, 2018) @@ -2077,38 +1970,38 @@ def test_deserialize_datetime(self): self.assertEqual(utc.tm_sec, 24) self.assertEqual(a.microsecond, 666666) - #with self.assertRaises(DeserializationError): + # with self.assertRaises(DeserializationError): # a = Deserializer.deserialize_iso('1996-01-01T23:01:54-22:66') #TODO with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('1996-01-01T23:01:54-24:30') + a = Deserializer.deserialize_iso("1996-01-01T23:01:54-24:30") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('1996-01-01T23:01:78+00:30') + a = Deserializer.deserialize_iso("1996-01-01T23:01:78+00:30") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('1996-01-01T23:60:01+00:30') + a = Deserializer.deserialize_iso("1996-01-01T23:60:01+00:30") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('1996-01-01T24:01:01+00:30') + a = Deserializer.deserialize_iso("1996-01-01T24:01:01+00:30") - #with self.assertRaises(DeserializationError): + # with self.assertRaises(DeserializationError): # a = Deserializer.deserialize_iso('1996-01-01t01:01:01/00:30') #TODO with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('1996-01-01F01:01:01+00:30') + a = Deserializer.deserialize_iso("1996-01-01F01:01:01+00:30") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('2015-02-32') + a = Deserializer.deserialize_iso("2015-02-32") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('2015-22-01') + a = Deserializer.deserialize_iso("2015-22-01") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('2010-13-31') + a = Deserializer.deserialize_iso("2010-13-31") with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('99999-12-31') + a = Deserializer.deserialize_iso("99999-12-31") with self.assertRaises(DeserializationError): a = Deserializer.deserialize_iso(True) @@ -2120,9 +2013,9 @@ def test_deserialize_datetime(self): a = Deserializer.deserialize_iso(None) with self.assertRaises(DeserializationError): - a = Deserializer.deserialize_iso('Happy New Year 2016') + a = Deserializer.deserialize_iso("Happy New Year 2016") - a = Deserializer.deserialize_iso('2012-02-24T00:53:52.780Z') + a = Deserializer.deserialize_iso("2012-02-24T00:53:52.780Z") utc = a.utctimetuple() self.assertEqual(utc.tm_year, 2012) @@ -2197,21 +2090,21 @@ def test_rfc_pickable(self): assert datetime1 == datetime2 def test_deserialize_decimal(self): - result = self.d.deserialize_data(0.33333, 'decimal') - self.assertEqual(result, decimal.Decimal('0.33333')) + result = self.d.deserialize_data(0.33333, "decimal") + self.assertEqual(result, decimal.Decimal("0.33333")) - result = self.d.deserialize_data('0.33333', 'decimal') - self.assertEqual(result, decimal.Decimal('0.33333')) + result = self.d.deserialize_data("0.33333", "decimal") + self.assertEqual(result, decimal.Decimal("0.33333")) with self.assertRaises(DeserializationError): - self.d.deserialize_data('not a decimal', 'decimal') + self.d.deserialize_data("not a decimal", "decimal") def test_polymorphic_deserialization(self): class Zoo(Model): _attribute_map = { - "animals":{"key":"Animals", "type":"[Animal]"}, + "animals": {"key": "Animals", "type": "[Animal]"}, } def __init__(self, animals=None): @@ -2219,14 +2112,9 @@ def __init__(self, animals=None): class Animal(Model): - _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "d_type":{"key":"dType", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}, "d_type": {"key": "dType", "type": "str"}} - _subtype_map = { - 'd_type': {"cat":"Cat", "dog":"Dog"} - } + _subtype_map = {"d_type": {"cat": "Cat", "dog": "Dog"}} def __init__(self, name=None): self.name = name @@ -2234,75 +2122,62 @@ def __init__(self, name=None): class Dog(Animal): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_dog_food":{"key":"likesDogFood","type":"bool"}, - "d_type":{"key":"dType", "type":"str"} - } + "name": {"key": "Name", "type": "str"}, + "likes_dog_food": {"key": "likesDogFood", "type": "bool"}, + "d_type": {"key": "dType", "type": "str"}, + } def __init__(self, name=None, likes_dog_food=None): self.likes_dog_food = likes_dog_food super(Dog, self).__init__(name) - self.d_type = 'dog' + self.d_type = "dog" class Cat(Animal): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_mice":{"key":"likesMice","type":"bool"}, - "dislikes":{"key":"dislikes","type":"Animal"}, - "d_type":{"key":"dType", "type":"str"} - } + "name": {"key": "Name", "type": "str"}, + "likes_mice": {"key": "likesMice", "type": "bool"}, + "dislikes": {"key": "dislikes", "type": "Animal"}, + "d_type": {"key": "dType", "type": "str"}, + } - _subtype_map = { - "d_type":{"siamese":"Siamese"} - } + _subtype_map = {"d_type": {"siamese": "Siamese"}} - def __init__(self, name=None, likes_mice=None, dislikes = None): + def __init__(self, name=None, likes_mice=None, dislikes=None): self.likes_mice = likes_mice self.dislikes = dislikes super(Cat, self).__init__(name) - self.d_type = 'cat' + self.d_type = "cat" class Siamese(Cat): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_mice":{"key":"likesMice","type":"bool"}, - "dislikes":{"key":"dislikes","type":"Animal"}, - "color":{"key":"Color", "type":"str"}, - "d_type":{"key":"dType", "type":"str"} - } - - def __init__(self, name=None, likes_mice=None, dislikes = None, color=None): + "name": {"key": "Name", "type": "str"}, + "likes_mice": {"key": "likesMice", "type": "bool"}, + "dislikes": {"key": "dislikes", "type": "Animal"}, + "color": {"key": "Color", "type": "str"}, + "d_type": {"key": "dType", "type": "str"}, + } + + def __init__(self, name=None, likes_mice=None, dislikes=None, color=None): self.color = color super(Siamese, self).__init__(name, likes_mice, dislikes) - self.d_type = 'siamese' + self.d_type = "siamese" message = { - "Animals": [{ - "dType": "dog", - "likesDogFood": True, - "Name": "Fido" - },{ - "dType": "cat", - "likesMice": False, - "dislikes": { - "dType": "dog", - "likesDogFood": True, - "Name": "Angry" + "Animals": [ + {"dType": "dog", "likesDogFood": True, "Name": "Fido"}, + { + "dType": "cat", + "likesMice": False, + "dislikes": {"dType": "dog", "likesDogFood": True, "Name": "Angry"}, + "Name": "Felix", }, - "Name": "Felix" - },{ - "dType": "siamese", - "Color": "grey", - "likesMice": True, - "Name": "Finch" - }] + {"dType": "siamese", "Color": "grey", "likesMice": True, "Name": "Finch"}, + ] } - self.d.dependencies = { - 'Zoo':Zoo, 'Animal':Animal, 'Dog':Dog, - 'Cat':Cat, 'Siamese':Siamese} + self.d.dependencies = {"Zoo": Zoo, "Animal": Animal, "Dog": Dog, "Cat": Cat, "Siamese": Siamese} zoo = self.d(Zoo, message) animals = [a for a in zoo.animals] @@ -2310,55 +2185,41 @@ def __init__(self, name=None, likes_mice=None, dislikes = None, color=None): self.assertEqual(len(animals), 3) self.assertIsInstance(animals[0], Dog) self.assertTrue(animals[0].likes_dog_food) - self.assertEqual(animals[0].name, message['Animals'][0]["Name"]) + self.assertEqual(animals[0].name, message["Animals"][0]["Name"]) self.assertIsInstance(animals[1], Cat) self.assertFalse(animals[1].likes_mice) self.assertIsInstance(animals[1].dislikes, Dog) - self.assertEqual(animals[1].dislikes.name, message['Animals'][1]["dislikes"]["Name"]) - self.assertEqual(animals[1].name, message['Animals'][1]["Name"]) + self.assertEqual(animals[1].dislikes.name, message["Animals"][1]["dislikes"]["Name"]) + self.assertEqual(animals[1].name, message["Animals"][1]["Name"]) self.assertIsInstance(animals[2], Siamese) - self.assertEqual(animals[2].color, message['Animals'][2]["Color"]) + self.assertEqual(animals[2].color, message["Animals"][2]["Color"]) self.assertTrue(animals[2].likes_mice) - message = { - "Name": "Didier", - "dType": "Animal" - } + message = {"Name": "Didier", "dType": "Animal"} animal = self.d(Animal, message) self.assertIsInstance(animal, Animal) self.assertEqual(animal.name, "Didier") - @unittest.skipIf(sys.version_info < (3,4), "assertLogs not supported before 3.4") + @unittest.skipIf(sys.version_info < (3, 4), "assertLogs not supported before 3.4") def test_polymorphic_missing_info(self): class Animal(Model): - _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "d_type":{"key":"dType", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}, "d_type": {"key": "dType", "type": "str"}} - _subtype_map = { - 'd_type': {} - } + _subtype_map = {"d_type": {}} def __init__(self, name=None): self.name = name - message = { - "Name": "Didier" - } - with self.assertLogs('storage_models.serialization', level="WARNING"): + message = {"Name": "Didier"} + with self.assertLogs("storage_models.serialization", level="WARNING"): animal = self.d(Animal, message) self.assertEqual(animal.name, "Didier") - message = { - "dType": "Penguin", - "likesDogFood": True, - "Name": "Fido" - } - with self.assertLogs('storage_models.serialization', level="WARNING"): + message = {"dType": "Penguin", "likesDogFood": True, "Name": "Fido"} + with self.assertLogs("storage_models.serialization", level="WARNING"): animal = self.d(Animal, message) self.assertEqual(animal.name, "Fido") @@ -2366,14 +2227,9 @@ def test_polymorphic_deserialization_with_escape(self): class Animal(Model): - _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "d_type":{"key":"odata\\.type", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}, "d_type": {"key": "odata\\.type", "type": "str"}} - _subtype_map = { - 'd_type': {"dog":"Dog"} - } + _subtype_map = {"d_type": {"dog": "Dog"}} def __init__(self, name=None): self.name = name @@ -2381,26 +2237,21 @@ def __init__(self, name=None): class Dog(Animal): _attribute_map = { - "name":{"key":"Name", "type":"str"}, - "likes_dog_food":{"key":"likesDogFood","type":"bool"}, - "d_type":{"key":"odata\\.type", "type":"str"} - } + "name": {"key": "Name", "type": "str"}, + "likes_dog_food": {"key": "likesDogFood", "type": "bool"}, + "d_type": {"key": "odata\\.type", "type": "str"}, + } def __init__(self, name=None, likes_dog_food=None): self.likes_dog_food = likes_dog_food super(Dog, self).__init__(name) - self.d_type = 'dog' + self.d_type = "dog" - message = { - "odata.type": "dog", - "likesDogFood": True, - "Name": "Fido" - } + message = {"odata.type": "dog", "likesDogFood": True, "Name": "Fido"} - self.d.dependencies = { - 'Animal':Animal, 'Dog':Dog} + self.d.dependencies = {"Animal": Animal, "Dog": Dog} - animal = self.d('Animal', message) + animal = self.d("Animal", message) self.assertIsInstance(animal, Dog) self.assertTrue(animal.likes_dog_food) @@ -2410,9 +2261,9 @@ def test_additional_properties(self): class AdditionalTest(Model): _attribute_map = { - "name": {"key":"Name", "type":"str"}, - "display_name": {"key":"DisplayName", "type":"str"}, - 'additional_properties': {'key': '', 'type': '{object}'} + "name": {"key": "Name", "type": "str"}, + "display_name": {"key": "DisplayName", "type": "str"}, + "additional_properties": {"key": "", "type": "{object}"}, } message = { @@ -2420,28 +2271,28 @@ class AdditionalTest(Model): "DisplayName": "diplay_name", "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, } - d = Deserializer({'AdditionalTest': AdditionalTest}) + d = Deserializer({"AdditionalTest": AdditionalTest}) - m = d('AdditionalTest', message) + m = d("AdditionalTest", message) self.assertEqual(m.name, "test") self.assertEqual(m.display_name, "diplay_name") - self.assertEqual(m.additional_properties['PropInt'], 2) - self.assertEqual(m.additional_properties['PropStr'], "AdditionalProperty") - self.assertEqual(m.additional_properties['PropArray'], [1,2,3]) - self.assertEqual(m.additional_properties['PropDict'], {"a": "b"}) + self.assertEqual(m.additional_properties["PropInt"], 2) + self.assertEqual(m.additional_properties["PropStr"], "AdditionalProperty") + self.assertEqual(m.additional_properties["PropArray"], [1, 2, 3]) + self.assertEqual(m.additional_properties["PropDict"], {"a": "b"}) def test_additional_properties_declared(self): class AdditionalTest(Model): _attribute_map = { - "name": {"key":"Name", "type":"str"}, - 'additional_properties': {'key': 'AddProp', 'type': '{object}'} + "name": {"key": "Name", "type": "str"}, + "additional_properties": {"key": "AddProp", "type": "{object}"}, } def __init__(self, name=None, additional_properties=None): @@ -2450,32 +2301,24 @@ def __init__(self, name=None, additional_properties=None): message = { "Name": "test", - "AddProp": { - "PropInt": 2, - "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} - } + "AddProp": {"PropInt": 2, "PropStr": "AdditionalProperty", "PropArray": [1, 2, 3], "PropDict": {"a": "b"}}, } - d = Deserializer({'AdditionalTest': AdditionalTest}) + d = Deserializer({"AdditionalTest": AdditionalTest}) - m = d('AdditionalTest', message) + m = d("AdditionalTest", message) self.assertEqual(m.name, "test") - self.assertEqual(m.additional_properties['PropInt'], 2) - self.assertEqual(m.additional_properties['PropStr'], "AdditionalProperty") - self.assertEqual(m.additional_properties['PropArray'], [1,2,3]) - self.assertEqual(m.additional_properties['PropDict'], {"a": "b"}) - + self.assertEqual(m.additional_properties["PropInt"], 2) + self.assertEqual(m.additional_properties["PropStr"], "AdditionalProperty") + self.assertEqual(m.additional_properties["PropArray"], [1, 2, 3]) + self.assertEqual(m.additional_properties["PropDict"], {"a": "b"}) def test_additional_properties_not_configured(self): class AdditionalTest(Model): - _attribute_map = { - "name": {"key":"Name", "type":"str"} - } + _attribute_map = {"name": {"key": "Name", "type": "str"}} def __init__(self, name=None): self.name = name @@ -2484,27 +2327,27 @@ def __init__(self, name=None): "Name": "test", "PropInt": 2, "PropStr": "AdditionalProperty", - "PropArray": [1,2,3], - "PropDict": {"a": "b"} + "PropArray": [1, 2, 3], + "PropDict": {"a": "b"}, } - d = Deserializer({'AdditionalTest': AdditionalTest}) + d = Deserializer({"AdditionalTest": AdditionalTest}) - m = d('AdditionalTest', message) + m = d("AdditionalTest", message) self.assertEqual(m.name, "test") - self.assertEqual(m.additional_properties['PropInt'], 2) - self.assertEqual(m.additional_properties['PropStr'], "AdditionalProperty") - self.assertEqual(m.additional_properties['PropArray'], [1,2,3]) - self.assertEqual(m.additional_properties['PropDict'], {"a": "b"}) + self.assertEqual(m.additional_properties["PropInt"], 2) + self.assertEqual(m.additional_properties["PropStr"], "AdditionalProperty") + self.assertEqual(m.additional_properties["PropArray"], [1, 2, 3]) + self.assertEqual(m.additional_properties["PropDict"], {"a": "b"}) def test_additional_properties_flattening(self): class AdditionalTest(Model): _attribute_map = { - "name": {"key":"Name", "type":"str"}, - "content" :{"key":"Properties.Content", "type":"str"} + "name": {"key": "Name", "type": "str"}, + "content": {"key": "Properties.Content", "type": "str"}, } def __init__(self, name=None, content=None): @@ -2512,17 +2355,11 @@ def __init__(self, name=None, content=None): self.name = name self.content = content - message = { - "Name": "test", - "Properties": { - "Content": "Content", - "Unknown": "Unknown" - } - } + message = {"Name": "test", "Properties": {"Content": "Content", "Unknown": "Unknown"}} - d = Deserializer({'AdditionalTest': AdditionalTest}) + d = Deserializer({"AdditionalTest": AdditionalTest}) - m = d('AdditionalTest', message) + m = d("AdditionalTest", message) self.assertEqual(m.name, "test") self.assertEqual(m.content, "Content") @@ -2533,47 +2370,33 @@ def test_attr_enum(self): Test deserializing with Enum. """ - test_obj = type("TestEnumObj", (Model,), {"_attribute_map":None}) - test_obj._attribute_map = { - "abc":{"key":"ABC", "type":"TestEnum"} - } + test_obj = type("TestEnumObj", (Model,), {"_attribute_map": None}) + test_obj._attribute_map = {"abc": {"key": "ABC", "type": "TestEnum"}} + class TestEnum(Enum): val = "Value" - deserializer = Deserializer({ - 'TestEnumObj': test_obj, - 'TestEnum': TestEnum - }) + deserializer = Deserializer({"TestEnumObj": test_obj, "TestEnum": TestEnum}) - obj = deserializer('TestEnumObj', { - 'ABC': 'Value' - }) + obj = deserializer("TestEnumObj", {"ABC": "Value"}) self.assertEqual(obj.abc, TestEnum.val) - obj = deserializer('TestEnumObj', { - 'ABC': 'azerty' - }) + obj = deserializer("TestEnumObj", {"ABC": "azerty"}) - self.assertEqual(obj.abc, 'azerty') + self.assertEqual(obj.abc, "azerty") class TestEnum2(Enum): val2 = "Value" - deserializer = Deserializer({ - 'TestEnumObj': test_obj, - 'TestEnum': TestEnum, - 'TestEnum2': TestEnum2 - }) + deserializer = Deserializer({"TestEnumObj": test_obj, "TestEnum": TestEnum, "TestEnum2": TestEnum2}) - obj = deserializer('TestEnumObj', { - 'ABC': TestEnum2.val2 - }) + obj = deserializer("TestEnumObj", {"ABC": TestEnum2.val2}) self.assertEqual(obj.abc, TestEnum.val) def test_long_as_type_object(self): """Test irrelevant on Python 3. But still doing it to test regression. - https://github.com/Azure/msrest-for-python/pull/121 + https://github.com/Azure/msrest-for-python/pull/121 """ try: @@ -2581,12 +2404,11 @@ def test_long_as_type_object(self): except NameError: long_type = int - class TestModel(Model): - _attribute_map = {'data': {'key': 'data', 'type': 'object'}} + _attribute_map = {"data": {"key": "data", "type": "object"}} - m = TestModel.deserialize({'data': {'id': long_type(1)}}) - assert m.data['id'] == long_type(1) + m = TestModel.deserialize({"data": {"id": long_type(1)}}) + assert m.data["id"] == long_type(1) def test_failsafe_deserialization(self): class Error(Model): @@ -2601,20 +2423,20 @@ def __init__(self, **kwargs): self.status = kwargs.get("status", None) self.message = kwargs.get("message", None) - with pytest.raises(DeserializationError): - self.d(Error, json.dumps(''), 'text/html') + self.d(Error, json.dumps(""), "text/html") # should fail - deserialized = self.d.failsafe_deserialize(Error, json.dumps(''), 'text/html') + deserialized = self.d.failsafe_deserialize(Error, json.dumps(""), "text/html") assert deserialized is None # should not fail error = {"status": 400, "message": "should deserialize"} - deserialized = self.d.failsafe_deserialize(Error, json.dumps(error), 'application/json') + deserialized = self.d.failsafe_deserialize(Error, json.dumps(error), "application/json") assert deserialized.status == 400 assert deserialized.message == "should deserialize" + class TestModelInstanceEquality(unittest.TestCase): def test_model_instance_equality(self): @@ -2622,17 +2444,18 @@ def test_model_instance_equality(self): class Animal(Model): _attribute_map = { - "name":{"key":"Name", "type":"str"}, + "name": {"key": "Name", "type": "str"}, } def __init__(self, name=None): self.name = name - animal1 = Animal('a1') - animal2 = Animal('a2') - animal3 = Animal('a1') - self.assertTrue(animal1!=animal2) - self.assertTrue(animal1==animal3) + animal1 = Animal("a1") + animal2 = Animal("a2") + animal3 = Animal("a1") + self.assertTrue(animal1 != animal2) + self.assertTrue(animal1 == animal3) + class TestAzureCoreExceptions(unittest.TestCase): @@ -2640,6 +2463,7 @@ def test_azure_core_exceptions(self): self.assertEqual(SerializationError, AzureCoreSerializationError) self.assertEqual(DeserializationError, AzureCoreDeserializationError) + class TestUrlEncoding(unittest.TestCase): # https://github.com/Azure/autorest.python/issues/2063 @@ -2652,5 +2476,6 @@ def test_skip_url_encoding(self): self.assertEqual("/database/%7BObject.value%7D", result1) self.assertEqual("%2Fdatabase%2F%7BObject.value%7D", result2) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_additional_properties.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_additional_properties.py index 80b01465ca4..8f3c9719c7e 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_additional_properties.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_additional_properties.py @@ -42,115 +42,82 @@ PetAPObject, PetAPString, PetAPInProperties, - PetAPInPropertiesWithAPString + PetAPInPropertiesWithAPString, ) import pytest + @pytest.fixture @async_generator async def client(): async with AdditionalPropertiesClient(base_url="http://localhost:3000") as client: await yield_(client) + class TestAdditionalProperties(object): @pytest.mark.asyncio async def test_create_ap_true(self, client): input_ap_true = PetAPTrue( - id = 1, - name = 'Puppy', - additional_properties = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - } + id=1, + name="Puppy", + additional_properties={"birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}}, ) output_ap_true = await client.pets.create_ap_true(input_ap_true) - assert output_ap_true.additional_properties['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true.additional_properties["birthdate"] == "2017-12-13T02:29:51Z" @pytest.mark.asyncio async def test_create_cat_ap_true(self, client): input_ap_true = CatAPTrue( - id = 1, - name = 'Lisa', - friendly = True, - additional_properties = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - } + id=1, + name="Lisa", + friendly=True, + additional_properties={"birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}}, ) output_ap_true = await client.pets.create_cat_ap_true(input_ap_true) - assert output_ap_true.additional_properties['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true.additional_properties["birthdate"] == "2017-12-13T02:29:51Z" @pytest.mark.asyncio async def test_create_ap_object(self, client): input_ap_obj = PetAPObject( - id = 2, - name = 'Hira', - additional_properties = { - 'siblings': [{ - 'id': 1, - 'name': 'Puppy', - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - }], - 'picture': '//////4=' - } + id=2, + name="Hira", + additional_properties={ + "siblings": [ + {"id": 1, "name": "Puppy", "birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}} + ], + "picture": "//////4=", + }, ) output_ap_obj = await client.pets.create_ap_object(input_ap_obj) - assert output_ap_obj.additional_properties['siblings'][0]['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_obj.additional_properties["siblings"][0]["birthdate"] == "2017-12-13T02:29:51Z" @pytest.mark.asyncio async def test_create_ap_string(self, client): input_ap_str = PetAPString( - id = 3, - name = 'Tommy', - additional_properties = { - 'color': 'red', - 'weight': '10 kg', - 'city': 'Bombay' - } + id=3, name="Tommy", additional_properties={"color": "red", "weight": "10 kg", "city": "Bombay"} ) output_ap_str = await client.pets.create_ap_string(input_ap_str) - assert output_ap_str.additional_properties['color'] == 'red' + assert output_ap_str.additional_properties["color"] == "red" @pytest.mark.asyncio async def test_create_ap_in_properties(self, client): input_ap_int = PetAPInProperties( - id = 4, - name = 'Bunny', - additional_properties = { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } + id=4, name="Bunny", additional_properties={"height": 5.61, "weight": 599, "footsize": 11.5} ) output_ap_int = await client.pets.create_ap_in_properties(input_ap_int) - assert output_ap_int.additional_properties['weight'] == 599 + assert output_ap_int.additional_properties["weight"] == 599 @pytest.mark.asyncio async def test_create_ap_in_properties_with_ap_string(self, client): input_ap_str_add = PetAPInPropertiesWithAPString( - id = 5, - name = 'Funny', - odata_location = 'westus', - additional_properties = { - 'color': 'red', - 'city': 'Seattle', - 'food': 'tikka masala' - }, - additional_properties1 = { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } + id=5, + name="Funny", + odata_location="westus", + additional_properties={"color": "red", "city": "Seattle", "food": "tikka masala"}, + additional_properties1={"height": 5.61, "weight": 599, "footsize": 11.5}, ) output_ap_str_add = await client.pets.create_ap_in_properties_with_ap_string(input_ap_str_add) - assert output_ap_str_add.additional_properties['color'] == 'red' - assert output_ap_str_add.additional_properties1['weight'] == 599 + assert output_ap_str_add.additional_properties["color"] == "red" + assert output_ap_str_add.additional_properties1["weight"] == 599 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_anything.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_anything.py index fcdbfe954ff..48946c29333 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_anything.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_anything.py @@ -27,32 +27,39 @@ from async_generator import yield_, async_generator from anything.aio import AnythingClient + @pytest.fixture @async_generator async def client(): async with AnythingClient(base_url="http://localhost:3000") as client: await yield_(client) + @pytest.mark.asyncio async def test_get_string(client): - assert await client.get_string() == 'anything' + assert await client.get_string() == "anything" + @pytest.mark.asyncio async def test_put_string(client): await client.put_string(input="anything") + @pytest.mark.asyncio async def test_get_object(client): assert await client.get_object() == {"message": "An object was successfully returned"} + @pytest.mark.asyncio async def test_put_object(client): - await client.put_object({'foo': 'bar'}) + await client.put_object({"foo": "bar"}) + @pytest.mark.asyncio async def test_get_array(client): - assert await client.get_array() == ['foo', 'bar'] + assert await client.get_array() == ["foo", "bar"] + @pytest.mark.asyncio async def test_put_array(client): - await client.put_array(['foo', 'bar']) + await client.put_array(["foo", "bar"]) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_array.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_array.py index 698936b2aa2..d8d067ad8c4 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_array.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_array.py @@ -42,12 +42,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATArrayService(base_url="http://localhost:3000") as client: await yield_(client) + @pytest.fixture def datetimes(): datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") @@ -55,6 +57,7 @@ def datetimes(): datetime3 = isodate.parse_datetime("1492-10-12T10:15:01Z") return [datetime1, datetime2, datetime3] + @pytest.fixture def products(): prod1 = Product(integer=1, string="2") @@ -62,68 +65,80 @@ def products(): prod3 = Product(integer=5, string="6") return [prod1, prod2, prod3] + @pytest.fixture def listdict(): - return [{"1": "one", "2": "two", "3": "three"}, - {"4": "four", "5": "five", "6": "six"}, - {"7": "seven", "8": "eight", "9": "nine"}] + return [ + {"1": "one", "2": "two", "3": "three"}, + {"4": "four", "5": "five", "6": "six"}, + {"7": "seven", "8": "eight", "9": "nine"}, + ] + class TestArray(object): @pytest.mark.asyncio async def test_empty(self, client): - assert [] == (await client.array.get_empty()) + assert [] == (await client.array.get_empty()) assert await client.array.get_null() is None await client.array.put_empty([]) @pytest.mark.asyncio async def test_boolean_tfft(self, client): - assert [True, False, False, True] == (await client.array.get_boolean_tfft()) + assert [True, False, False, True] == (await client.array.get_boolean_tfft()) await client.array.put_boolean_tfft([True, False, False, True]) @pytest.mark.asyncio async def test_integer_valid(self, client): - assert [1, -1, 3, 300] == (await client.array.get_integer_valid()) + assert [1, -1, 3, 300] == (await client.array.get_integer_valid()) await client.array.put_integer_valid([1, -1, 3, 300]) @pytest.mark.asyncio async def test_long_valid(self, client): - assert [1, -1, 3, 300] == (await client.array.get_long_valid()) + assert [1, -1, 3, 300] == (await client.array.get_long_valid()) await client.array.put_long_valid([1, -1, 3, 300]) @pytest.mark.asyncio async def test_float_valid(self, client): - assert [0, -0.01, -1.2e20] == (await client.array.get_float_valid()) + assert [0, -0.01, -1.2e20] == (await client.array.get_float_valid()) await client.array.put_float_valid([0, -0.01, -1.2e20]) @pytest.mark.asyncio async def test_double_valid(self, client): - assert [0, -0.01, -1.2e20] == (await client.array.get_double_valid()) + assert [0, -0.01, -1.2e20] == (await client.array.get_double_valid()) await client.array.put_double_valid([0, -0.01, -1.2e20]) @pytest.mark.asyncio async def test_string_valid(self, client): - assert ["foo1", "foo2", "foo3"] == (await client.array.get_string_valid()) + assert ["foo1", "foo2", "foo3"] == (await client.array.get_string_valid()) await client.array.put_string_valid(["foo1", "foo2", "foo3"]) @pytest.mark.asyncio async def test_get_string_with_null(self, client): - assert ["foo", None, "foo2"] == (await client.array.get_string_with_null()) + assert ["foo", None, "foo2"] == (await client.array.get_string_with_null()) @pytest.mark.asyncio async def test_get_string_with_invalid(self, client): - assert ["foo", "123", "foo2"] == (await client.array.get_string_with_invalid()) + assert ["foo", "123", "foo2"] == (await client.array.get_string_with_invalid()) @pytest.mark.asyncio async def test_uuid_valid(self, client): - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"] == (await client.array.get_uuid_valid()) - await client.array.put_uuid_valid(["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"]) + assert [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] == (await client.array.get_uuid_valid()) + await client.array.put_uuid_valid( + [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] + ) @pytest.mark.asyncio async def test_get_uuid_invalid_chars(self, client): - #Handles invalid characters without error because of no guid class - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == (await client.array.get_uuid_invalid_chars()) + # Handles invalid characters without error because of no guid class + assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == (await client.array.get_uuid_invalid_chars()) @pytest.mark.asyncio async def test_date_valid(self, client): @@ -132,19 +147,19 @@ async def test_date_valid(self, client): date3 = isodate.parse_date("1492-10-12") date_array = await client.array.get_date_valid() - assert date_array, [date1, date2 == date3] + assert date_array, [date1, date2 == date3] await client.array.put_date_valid([date1, date2, date3]) @pytest.mark.asyncio async def test_date_time_valid(self, client, datetimes): dt_array = await client.array.get_date_time_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] await client.array.put_date_time_valid(datetimes) @pytest.mark.asyncio async def test_date_time_rfc1123_valid(self, client, datetimes): dt_array = await client.array.get_date_time_rfc1123_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] await client.array.put_date_time_rfc1123_valid(datetimes) @pytest.mark.asyncio @@ -153,7 +168,7 @@ async def test_duration_valid(self, client): duration2 = timedelta(days=5, hours=1) dur_array = await client.array.get_duration_valid() - assert dur_array, [duration1 == duration2] + assert dur_array, [duration1 == duration2] await client.array.put_duration_valid([duration1, duration2]) @pytest.mark.asyncio @@ -164,12 +179,12 @@ async def test_byte_valid(self, client): await client.array.put_byte_valid([bytes1, bytes2, bytes3]) bytes_array = await client.array.get_byte_valid() - assert bytes_array, [bytes1, bytes2 == bytes3] + assert bytes_array, [bytes1, bytes2 == bytes3] @pytest.mark.asyncio async def test_get_byte_invalid_null(self, client): bytes_array = await client.array.get_byte_invalid_null() - assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] + assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] @pytest.mark.asyncio async def test_get_complex_null(self, client): @@ -177,34 +192,34 @@ async def test_get_complex_null(self, client): @pytest.mark.asyncio async def test_get_complex_empty(self, client): - assert [] == (await client.array.get_complex_empty()) + assert [] == (await client.array.get_complex_empty()) @pytest.mark.asyncio async def test_complex_valid(self, client, products): await client.array.put_complex_valid(products) - assert products == (await client.array.get_complex_valid()) + assert products == (await client.array.get_complex_valid()) @pytest.mark.asyncio async def test_array_valid(self, client): listlist = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] await client.array.put_array_valid(listlist) - assert listlist == (await client.array.get_array_valid()) + assert listlist == (await client.array.get_array_valid()) @pytest.mark.asyncio async def test_dictionary_valid(self, client, listdict): await client.array.put_dictionary_valid(listdict) - assert listdict == (await client.array.get_dictionary_valid()) + assert listdict == (await client.array.get_dictionary_valid()) @pytest.mark.asyncio async def test_get_complex_item_null(self, client, products): products_null = [products[0], None, products[2]] - assert products_null == (await client.array.get_complex_item_null()) + assert products_null == (await client.array.get_complex_item_null()) @pytest.mark.asyncio async def test_get_complex_item_empty(self, client, products): products_empty = [products[0], Product(), products[2]] - assert products_empty == (await client.array.get_complex_item_empty()) + assert products_empty == (await client.array.get_complex_item_empty()) @pytest.mark.asyncio async def test_get_array_null(self, client): @@ -212,31 +227,31 @@ async def test_get_array_null(self, client): @pytest.mark.asyncio async def test_get_array_empty(self, client): - assert [] == (await client.array.get_array_empty()) + assert [] == (await client.array.get_array_empty()) @pytest.mark.asyncio async def test_get_array_item_null(self, client): listlist2 = [["1", "2", "3"], None, ["7", "8", "9"]] - assert listlist2 == (await client.array.get_array_item_null()) + assert listlist2 == (await client.array.get_array_item_null()) @pytest.mark.asyncio async def test_get_array_item_empty(self, client): listlist3 = [["1", "2", "3"], [], ["7", "8", "9"]] - assert listlist3 == (await client.array.get_array_item_empty()) + assert listlist3 == (await client.array.get_array_item_empty()) @pytest.mark.asyncio async def test_get_dictionary_and_dictionary_item_null(self, client, listdict): assert (await client.array.get_dictionary_null()) is None listdict[1] = None - assert listdict == (await client.array.get_dictionary_item_null()) + assert listdict == (await client.array.get_dictionary_item_null()) @pytest.mark.asyncio async def test_get_dictionary_and_dictionary_item_empty(self, client, listdict): - assert [] == (await client.array.get_dictionary_empty()) + assert [] == (await client.array.get_dictionary_empty()) listdict[1] = {} - assert listdict == (await client.array.get_dictionary_item_empty()) + assert listdict == (await client.array.get_dictionary_item_empty()) @pytest.mark.asyncio async def test_array_get_invalid(self, client): @@ -245,7 +260,7 @@ async def test_array_get_invalid(self, client): @pytest.mark.asyncio async def test_array_get_boolean_invalid_null(self, client): - assert await client.array.get_boolean_invalid_null(), [True, None == False] + assert await client.array.get_boolean_invalid_null(), [True, None == False] @pytest.mark.asyncio async def test_array_get_boolean_invalid_string(self, client): @@ -254,7 +269,7 @@ async def test_array_get_boolean_invalid_string(self, client): @pytest.mark.asyncio async def test_array_get_int_invalid_null(self, client): - assert await client.array.get_int_invalid_null(), [1, None == 0] + assert await client.array.get_int_invalid_null(), [1, None == 0] @pytest.mark.asyncio async def test_array_get_int_invalid_string(self, client): @@ -263,7 +278,7 @@ async def test_array_get_int_invalid_string(self, client): @pytest.mark.asyncio async def test_array_get_long_invalid_null(self, client): - assert await client.array.get_long_invalid_null(), [1, None == 0] + assert await client.array.get_long_invalid_null(), [1, None == 0] @pytest.mark.asyncio async def test_array_get_long_invalid_string(self, client): @@ -272,7 +287,7 @@ async def test_array_get_long_invalid_string(self, client): @pytest.mark.asyncio async def test_array_get_float_invalid_null(self, client): - assert await client.array.get_float_invalid_null(), [0.0, None == -1.2e20] + assert await client.array.get_float_invalid_null(), [0.0, None == -1.2e20] @pytest.mark.asyncio async def test_array_get_float_invalid_string(self, client): @@ -281,7 +296,7 @@ async def test_array_get_float_invalid_string(self, client): @pytest.mark.asyncio async def test_array_get_double_invalid_null(self, client): - assert await client.array.get_double_invalid_null(), [0.0, None == -1.2e20] + assert await client.array.get_double_invalid_null(), [0.0, None == -1.2e20] @pytest.mark.asyncio async def test_array_get_double_invalid_string(self, client): @@ -290,12 +305,12 @@ async def test_array_get_double_invalid_string(self, client): @pytest.mark.asyncio async def test_array_get_string_with_invalid(self, client): - assert await client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] + assert await client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] @pytest.mark.asyncio async def test_array_get_date_invalid_null(self, client): d_array = await client.array.get_date_invalid_null() - assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] + assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] @pytest.mark.asyncio async def test_array_get_date_invalid_chars(self, client): @@ -305,7 +320,7 @@ async def test_array_get_date_invalid_chars(self, client): @pytest.mark.asyncio async def test_array_get_date_time_invalid_null(self, client): dt_array = await client.array.get_date_time_invalid_null() - assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] + assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] @pytest.mark.asyncio async def test_array_get_date_time_invalid_chars(self, client): @@ -314,10 +329,12 @@ async def test_array_get_date_time_invalid_chars(self, client): @pytest.mark.asyncio async def test_array_get_base64_url(self, client): - test_array = ['a string that gets encoded with base64url'.encode(), - 'test string'.encode(), - 'Lorem ipsum'.encode()] - assert (await client.array.get_base64_url()) == test_array + test_array = [ + "a string that gets encoded with base64url".encode(), + "test string".encode(), + "Lorem ipsum".encode(), + ] + assert (await client.array.get_base64_url()) == test_array @pytest.mark.asyncio async def test_array_enum_valid(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_binary.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_binary.py index 41a7f3ff733..f63bb100891 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_binary.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_binary.py @@ -28,6 +28,7 @@ from bodybinary.aio import BinaryWithContentTypeApplicationJson from azure.core.exceptions import HttpResponseError + @pytest.fixture async def client(): async with BinaryWithContentTypeApplicationJson() as client: @@ -38,10 +39,12 @@ async def client(): async def test_upload_file(client): await client.upload.file(json.dumps({"more": "cowbell"})) + @pytest.mark.asyncio async def test_upload_binary(client): await client.upload.binary(b"Hello, world!") + @pytest.mark.asyncio async def test_error(client): with pytest.raises(HttpResponseError): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_bool.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_bool.py index 2179b032287..42e918f3e10 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_bool.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_bool.py @@ -41,17 +41,19 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestBoolTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestBool(object): @pytest.mark.asyncio async def test_model_get_true(self, client): - assert (await client.bool.get_true()) + assert await client.bool.get_true() @pytest.mark.asyncio async def test_model_get_false(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_byte.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_byte.py index cc5dea7cc7f..c6b44bd85f9 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_byte.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_byte.py @@ -41,19 +41,21 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATByteService(base_url="http://localhost:3000") as client: await yield_(client) + class TestByte(object): @pytest.mark.asyncio async def test_non_ascii(self, client): tests = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x0FB, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) await client.byte.put_non_ascii(tests) - assert tests == (await client.byte.get_non_ascii()) + assert tests == (await client.byte.get_non_ascii()) @pytest.mark.asyncio async def test_get_null(self, client): @@ -61,7 +63,7 @@ async def test_get_null(self, client): @pytest.mark.asyncio async def test_get_empty(self, client): - assert bytearray() == (await client.byte.get_empty()) + assert bytearray() == (await client.byte.get_empty()) @pytest.mark.asyncio async def test_get_invalid(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_client_enum.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_client_enum.py index 70e1eef42b2..48faad69f53 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_client_enum.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_client_enum.py @@ -26,11 +26,13 @@ import pytest from clientenum import aio, models + @pytest.fixture async def client(): async with aio.ClientWithEnum(x_ms_enum=models.Enum0.SINGLE) as client: yield client + @pytest.mark.asyncio async def test_head(client): await client.head() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_complex.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_complex.py index b69abbe9392..6876a3e2b45 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_complex.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_complex.py @@ -42,16 +42,18 @@ from bodycomplex.aio import AutoRestComplexTestService from bodycomplex.models import * + class UTC(tzinfo): - def utcoffset(self,dt): - return timedelta(hours=0,minutes=0) + def utcoffset(self, dt): + return timedelta(hours=0, minutes=0) - def tzname(self,dt): + def tzname(self, dt): return "Z" - def dst(self,dt): + def dst(self, dt): return timedelta(0) + import pytest @@ -61,25 +63,27 @@ async def client(): async with AutoRestComplexTestService(base_url="http://localhost:3000") as client: await yield_(client) + @pytest.fixture def min_date(): min_date = datetime.min return min_date.replace(tzinfo=UTC()) + class TestComplex(object): @pytest.mark.asyncio async def test_basic_get_and_put_valid(self, client): # GET basic/valid basic_result = await client.basic.get_valid() - assert 2 == basic_result.id - assert "abc" == basic_result.name - assert CMYKColors.yellow.value == basic_result.color + assert 2 == basic_result.id + assert "abc" == basic_result.name + assert CMYKColors.yellow.value == basic_result.color # PUT basic/valid - basic_result = Basic(id=2, name='abc', color="Magenta") + basic_result = Basic(id=2, name="abc", color="Magenta") await client.basic.put_valid(basic_result) - basic_result = Basic(id=2, name='abc', color=CMYKColors.magenta) + basic_result = Basic(id=2, name="abc", color=CMYKColors.magenta) await client.basic.put_valid(basic_result) @pytest.mark.asyncio @@ -114,30 +118,30 @@ async def test_basic_get_invalid(self, client): async def test_primitive_get_and_put_int(self, client): # GET primitive/integer intResult = await client.primitive.get_int() - assert -1 == intResult.field1 - assert 2 == intResult.field2 + assert -1 == intResult.field1 + assert 2 == intResult.field2 # PUT primitive/integer - intRequest = {'field1':-1, 'field2':2} + intRequest = {"field1": -1, "field2": 2} await client.primitive.put_int(intRequest) @pytest.mark.asyncio async def test_primitive_get_and_put_long(self, client): # GET primitive/long longResult = await client.primitive.get_long() - assert 1099511627775 == longResult.field1 - assert -999511627788 == longResult.field2 + assert 1099511627775 == longResult.field1 + assert -999511627788 == longResult.field2 # PUT primitive/long - longRequest = {'field1':1099511627775, 'field2':-999511627788} + longRequest = {"field1": 1099511627775, "field2": -999511627788} await client.primitive.put_long(longRequest) @pytest.mark.asyncio async def test_primitive_get_and_put_float(self, client): # GET primitive/float floatResult = await client.primitive.get_float() - assert 1.05 == floatResult.field1 - assert -0.003 == floatResult.field2 + assert 1.05 == floatResult.field1 + assert -0.003 == floatResult.field2 # PUT primitive/float floatRequest = FloatWrapper(field1=1.05, field2=-0.003) @@ -147,12 +151,17 @@ async def test_primitive_get_and_put_float(self, client): async def test_primitive_get_and_put_double(self, client): # GET primitive/double doubleResult = await client.primitive.get_double() - assert 3e-100 == doubleResult.field1 - assert -5e-57 == doubleResult.field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose + assert 3e-100 == doubleResult.field1 + assert ( + -5e-57 + == doubleResult.field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose + ) # PUT primitive/double - doubleRequest = {'field1':3e-100} - doubleRequest['field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose'] = -5e-57 + doubleRequest = {"field1": 3e-100} + doubleRequest[ + "field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose" + ] = -5e-57 await client.primitive.put_double(doubleRequest) @pytest.mark.asyncio @@ -170,8 +179,8 @@ async def test_primitive_get_and_put_bool(self, client): async def test_primitive_get_and_put_string(self, client): # GET primitive/string stringResult = await client.primitive.get_string() - assert "goodrequest" == stringResult.field - assert "" == stringResult.empty + assert "goodrequest" == stringResult.field + assert "" == stringResult.empty assert stringResult.null is None # PUT primitive/string @@ -182,12 +191,10 @@ async def test_primitive_get_and_put_string(self, client): async def test_primitive_get_and_put_date(self, client): # GET primitive/date dateResult = await client.primitive.get_date() - assert isodate.parse_date("0001-01-01") == dateResult.field - assert isodate.parse_date("2016-02-29") == dateResult.leap + assert isodate.parse_date("0001-01-01") == dateResult.field + assert isodate.parse_date("2016-02-29") == dateResult.leap - dateRequest = DateWrapper( - field=isodate.parse_date('0001-01-01'), - leap=isodate.parse_date('2016-02-29')) + dateRequest = DateWrapper(field=isodate.parse_date("0001-01-01"), leap=isodate.parse_date("2016-02-29")) await client.primitive.put_date(dateRequest) @pytest.mark.asyncio @@ -195,11 +202,11 @@ async def test_primitive_get_and_put_date_time(self, client, min_date): # GET primitive/datetime datetimeResult = await client.primitive.get_date_time() - assert min_date == datetimeResult.field + assert min_date == datetimeResult.field datetime_request = DatetimeWrapper( - field=isodate.parse_datetime("0001-01-01T00:00:00Z"), - now=isodate.parse_datetime("2015-05-18T18:38:00Z")) + field=isodate.parse_datetime("0001-01-01T00:00:00Z"), now=isodate.parse_datetime("2015-05-18T18:38:00Z") + ) await client.primitive.put_date_time(datetime_request) @pytest.mark.asyncio @@ -210,20 +217,20 @@ async def test_primitive_get_and_put_date_time_rfc1123(self, client): # we are not using the min date of year 1 because of the latest msrest update # with msrest update, minimal year we can parse is 100, instead of 1 min_date = datetime(2001, 1, 1) - assert min_date.replace(tzinfo=UTC()) == datetimeRfc1123Result.field + assert min_date.replace(tzinfo=UTC()) == datetimeRfc1123Result.field # we can still model year 1 though with the latest msrest update datetime_request = Datetimerfc1123Wrapper( - field=isodate.parse_datetime("0001-01-01T00:00:00Z"), - now=isodate.parse_datetime("2015-05-18T11:38:00Z")) + field=isodate.parse_datetime("0001-01-01T00:00:00Z"), now=isodate.parse_datetime("2015-05-18T11:38:00Z") + ) await client.primitive.put_date_time_rfc1123(datetime_request) @pytest.mark.asyncio async def test_primitive_get_and_put_duration(self, client): # GET primitive/duration expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - assert expected == (await client.primitive.get_duration()).field + assert expected == (await client.primitive.get_duration()).field await client.primitive.put_duration(expected) @@ -232,7 +239,7 @@ async def test_primitive_get_and_put_byte(self, client): # GET primitive/byte byteResult = await client.primitive.get_byte() valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - assert valid_bytes == byteResult.field + assert valid_bytes == byteResult.field # PUT primitive/byte await client.primitive.put_byte(valid_bytes) @@ -243,9 +250,9 @@ async def test_primitive_get_and_put_byte(self, client): async def test_readonlyproperty_get_and_put_valid(self, client): # GET readonly/valid valid_obj = ReadonlyObj(size=2) - valid_obj.id = '1234' + valid_obj.id = "1234" readonly_result = await client.readonlyproperty.get_valid() - assert readonly_result == valid_obj + assert readonly_result == valid_obj # PUT readonly/valid readonly_result = await client.readonlyproperty.put_valid(2) @@ -257,11 +264,10 @@ async def test_readonlyproperty_get_and_put_valid(self, client): async def test_array_get_and_put_valid(self, client): # GET array/valid array_result = await client.array.get_valid() - assert 5 == len(array_result.array) + assert 5 == len(array_result.array) - array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", - "The quick brown fox jumps over the lazy dog"] - assert array_result.array == array_value + array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", "The quick brown fox jumps over the lazy dog"] + assert array_result.array == array_value # PUT array/valid await client.array.put_valid(array_value) @@ -271,7 +277,7 @@ async def test_array_get_and_put_empty(self, client): # GET array/empty array_result = await client.array.get_empty() - assert 0 == len(array_result.array) + assert 0 == len(array_result.array) # PUT array/empty await client.array.put_empty([]) @@ -287,10 +293,10 @@ async def test_array_get_not_provided(self, client): async def test_dictionary_get_and_put_valid(self, client): # GET dictionary/valid dict_result = await client.dictionary.get_valid() - assert 5 == len(dict_result.default_program) + assert 5 == len(dict_result.default_program) - dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} - assert dict_val == dict_result.default_program + dict_val = {"txt": "notepad", "bmp": "mspaint", "xls": "excel", "exe": "", "": None} + assert dict_val == dict_result.default_program # PUT dictionary/valid await client.dictionary.put_valid(dict_val) @@ -299,7 +305,7 @@ async def test_dictionary_get_and_put_valid(self, client): async def test_dictionary_get_and_put_empty(self, client): # GET dictionary/empty dict_result = await client.dictionary.get_empty() - assert 0 == len(dict_result.default_program) + assert 0 == len(dict_result.default_program) # PUT dictionary/empty await client.dictionary.put_empty(default_program={}) @@ -320,20 +326,19 @@ async def test_dictionary_get_not_provided(self, client): async def test_inheritance_get_and_put_valid(self, client): # GET inheritance/valid inheritanceResult = await client.inheritance.get_valid() - assert 2 == inheritanceResult.id - assert "Siameeee" == inheritanceResult.name - assert -1 == inheritanceResult.hates[1].id - assert "Tomato" == inheritanceResult.hates[1].name + assert 2 == inheritanceResult.id + assert "Siameeee" == inheritanceResult.name + assert -1 == inheritanceResult.hates[1].id + assert "Tomato" == inheritanceResult.hates[1].name # PUT inheritance/valid request = { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [Dog(id=1, name="Potato", food="tomato"), - Dog(id=-1, name="Tomato", food="french fries")] - } + "id": 2, + "name": "Siameeee", + "color": "green", + "breed": "persian", + "hates": [Dog(id=1, name="Potato", food="tomato"), Dog(id=-1, name="Tomato", food="french fries")], + } await client.inheritance.put_valid(request) # COMPLEX TYPES THAT INVOLVE POLYMORPHISM @@ -353,47 +358,56 @@ async def test_polymorphism_get_and_put_valid(self, client): # GET polymorphism/valid result = await client.polymorphism.get_valid() assert result is not None - assert result.location == "alaska" - assert len(result.siblings) == 3 - assert isinstance(result.siblings[0], Shark) - assert isinstance(result.siblings[1], Sawshark) - assert isinstance(result.siblings[2], Goblinshark) - assert result.siblings[0].age == 6 - assert result.siblings[1].age == 105 - assert result.siblings[2].age == 1 - + assert result.location == "alaska" + assert len(result.siblings) == 3 + assert isinstance(result.siblings[0], Shark) + assert isinstance(result.siblings[1], Sawshark) + assert isinstance(result.siblings[2], Goblinshark) + assert result.siblings[0].age == 6 + assert result.siblings[1].age == 105 + assert result.siblings[2].age == 1 # PUT polymorphism/valid - request = Salmon(length=1, - iswild = True, - location = "alaska", - species = "king", - siblings = [Shark(length=20, - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), - age=6, species="predator"), - Sawshark(length=10, - birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - age=105, species="dangerous", - picture=bytearray([255, 255, 255, 255, 254])), - Goblinshark(length=30, - birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), - age=1, species="scary", jawsize=5, color='pinkish-gray')] - ) + request = Salmon( + length=1, + iswild=True, + location="alaska", + species="king", + siblings=[ + Shark(length=20, birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), age=6, species="predator"), + Sawshark( + length=10, + birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), + age=105, + species="dangerous", + picture=bytearray([255, 255, 255, 255, 254]), + ), + Goblinshark( + length=30, + birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), + age=1, + species="scary", + jawsize=5, + color="pinkish-gray", + ), + ], + ) await client.polymorphism.put_valid(request) @pytest.mark.asyncio async def test_polymorphism_put_valid_missing_required(self, client): - bad_request = Salmon(length=1, + bad_request = Salmon( + length=1, iswild=True, location="alaska", species="king", - siblings = [ - Shark(length=20, - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), - age=6, species="predator"), - Sawshark(length=10, birthday=None, age=105, species="dangerous", - picture=bytearray([255, 255, 255, 255, 254]))] - ) + siblings=[ + Shark(length=20, birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), age=6, species="predator"), + Sawshark( + length=10, birthday=None, age=105, species="dangerous", picture=bytearray([255, 255, 255, 255, 254]) + ), + ], + ) with pytest.raises(ValidationError): await client.polymorphism.put_valid_missing_required(bad_request) @@ -404,10 +418,10 @@ async def test_polymorphism_put_valid_missing_required(self, client): async def test_polymorphismrecursive_get_and_put_valid(self, client): # GET polymorphicrecursive/valid result = await client.polymorphicrecursive.get_valid() - assert isinstance(result, Salmon) - assert isinstance(result.siblings[0], Shark) - assert isinstance(result.siblings[0].siblings[0], Salmon) - assert result.siblings[0].siblings[0].location == "atlantic" + assert isinstance(result, Salmon) + assert isinstance(result.siblings[0], Shark) + assert isinstance(result.siblings[0].siblings[0], Salmon) + assert result.siblings[0].siblings[0].location == "atlantic" request = Salmon( iswild=True, @@ -430,28 +444,38 @@ async def test_polymorphismrecursive_get_and_put_valid(self, client): age=6, length=20, species="predator", - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z")), + birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), + ), Sawshark( age=105, length=10, species="dangerous", birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]))]), + picture=bytearray([255, 255, 255, 255, 254]), + ), + ], + ), Sawshark( age=105, length=10, species="dangerous", siblings=[], birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]))], - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z")), + picture=bytearray([255, 255, 255, 255, 254]), + ), + ], + birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), + ), Sawshark( age=105, length=10, species="dangerous", siblings=[], birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]))]) + picture=bytearray([255, 255, 255, 255, 254]), + ), + ], + ) # PUT polymorphicrecursive/valid await client.polymorphicrecursive.put_valid(request) @@ -470,7 +494,6 @@ async def test_polymorphismrecursive_put_valid_stream(self, client): with open(path, "rb") as fd: await client.polymorphicrecursive.put_valid(fd) - # Complex types that uses additional properties and polymorphism @pytest.mark.asyncio async def test_polymorphism_get_and_put_complicated(self, client): @@ -483,28 +506,27 @@ async def test_polymorphism_get_and_put_complicated(self, client): async def test_polymorphism_get_and_put_missing_discriminator(self, client): regular_salmon = Salmon( iswild=True, - location='alaska', - species='king', + location="alaska", + species="king", length=1.0, - siblings=[Shark( - age=6, - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), - length=20, - species='predator' - ), Sawshark( - age=105, - length=10, - species="dangerous", - birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]) - ), Goblinshark( - length=30, - birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), - age=1, - species="scary", - jawsize=5, - color='pinkish-gray' - )] + siblings=[ + Shark(age=6, birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), length=20, species="predator"), + Sawshark( + age=105, + length=10, + species="dangerous", + birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), + picture=bytearray([255, 255, 255, 255, 254]), + ), + Goblinshark( + length=30, + birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), + age=1, + species="scary", + jawsize=5, + color="pinkish-gray", + ), + ], ) # Not raise is enough of a test await client.polymorphism.put_missing_discriminator(regular_salmon) @@ -522,13 +544,14 @@ async def test_pass_in_api_version(self, client): @pytest.mark.asyncio async def test_client_api_version(self): api_version = "2021-10-01" + def check_api_version(pipeline_request): assert pipeline_request.http_request.query["api-version"] == api_version - policies=[CustomHookPolicy(raw_request_hook=check_api_version)] + policies = [CustomHookPolicy(raw_request_hook=check_api_version)] async with AutoRestComplexTestService(api_version=api_version, policies=policies) as client: # PUT basic/valid - basic_result = Basic(id=2, name='abc', color="Magenta") + basic_result = Basic(id=2, name="abc", color="Magenta") await client.basic.put_valid(basic_result) # it shall raise exception since we override api_version diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_config.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_config.py index 8979434e2a2..453af699a25 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_config.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_config.py @@ -27,20 +27,26 @@ from azure.core.pipeline.policies import HttpLoggingPolicy from bodystring.aio import AutoRestSwaggerBATService + class TestConfig(object): @pytest.mark.asyncio async def test_http_logging_policy_default(self): async with AutoRestSwaggerBATService(base_url="http://localhost:3000") as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) @pytest.mark.asyncio async def test_http_logging_policy_custom(self): http_logging_policy = HttpLoggingPolicy(base_url="test") http_logging_policy = HttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) - async with AutoRestSwaggerBATService(base_url="http://localhost:3000", http_logging_policy=http_logging_policy) as client: + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) + async with AutoRestSwaggerBATService( + base_url="http://localhost:3000", http_logging_policy=http_logging_policy + ) as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_constants.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_constants.py index 315a89971c3..44c842042aa 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_constants.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_constants.py @@ -26,23 +26,24 @@ import pytest from constants.aio import AutoRestSwaggerConstantService + @pytest.fixture async def client(): async with AutoRestSwaggerConstantService(base_url="http://localhost:3000") as client: yield client + def test_put_client_constants(client): client.contants.put_client_constants() assert client._config.header_constant == True assert client._config.query_constant == 100 assert client._config.path_constant == "path" + @pytest.mark.asyncio async def test_put_client_constants_override(): async with AutoRestSwaggerConstantService( - header_constant=False, - query_constant=0, - path_constant="new_path" + header_constant=False, query_constant=0, path_constant="new_path" ) as client: assert client._config.header_constant == False assert client._config.query_constant == 0 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_custom_base_uri.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_custom_base_uri.py index 4dbbf2adc09..7dc1463a209 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_custom_base_uri.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_custom_base_uri.py @@ -42,12 +42,14 @@ import pytest + @pytest.fixture @async_generator async def client(): - async with AutoRestParameterizedHostTestClient("host:3000", retry_total = 0) as client: + async with AutoRestParameterizedHostTestClient("host:3000", retry_total=0) as client: await yield_(client) + class TestCustomBaseUri(object): @pytest.mark.asyncio @@ -67,7 +69,7 @@ async def test_get_empty_with_none(self, client): @pytest.mark.asyncio async def test_get_empty_from_bad_host(self): - async with AutoRestParameterizedHostTestClient("badhost:3000", retry_total = 0) as client: + async with AutoRestParameterizedHostTestClient("badhost:3000", retry_total=0) as client: with pytest.raises(ServiceRequestError): await client.paths.get_empty("local") diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_date.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_date.py index 28dc850020a..ff2107d9d74 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_date.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_date.py @@ -41,25 +41,27 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDateTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestDate(object): @pytest.mark.asyncio async def test_model_get_and_put_max_date(self, client): max_date = isodate.parse_date("9999-12-31T23:59:59.999999Z") await client.date.put_max_date(max_date) - assert max_date == (await client.date.get_max_date()) + assert max_date == (await client.date.get_max_date()) @pytest.mark.asyncio async def test_model_get_and_put_min_date(self, client): min_date = isodate.parse_date("0001-01-01T00:00:00Z") await client.date.put_min_date(min_date) - assert min_date == (await client.date.get_min_date()) + assert min_date == (await client.date.get_min_date()) @pytest.mark.asyncio async def test_model_get_null(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime.py index a45c61a961e..7958c4406c1 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime.py @@ -41,20 +41,22 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDateTimeTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestDatetime: @pytest.mark.asyncio async def test_utc_max_date_time(self, client): max_date = isodate.parse_datetime("9999-12-31T23:59:59.999Z") dt = await client.datetime.get_utc_lowercase_max_date_time() - assert dt == max_date + assert dt == max_date dt = await client.datetime.get_utc_uppercase_max_date_time() - assert dt == max_date + assert dt == max_date await client.datetime.put_utc_max_date_time(max_date) @pytest.mark.asyncio @@ -70,14 +72,15 @@ async def test_utc_max_date_time_7digits(self, client): async def test_get_utc_min_date_time(self, client): min_date = isodate.parse_datetime("0001-01-01T00:00:00Z") dt = await client.datetime.get_utc_min_date_time() - assert dt == min_date + assert dt == min_date await client.datetime.put_utc_min_date_time(min_date) @pytest.mark.asyncio async def test_get_local_negative_offset_min_date_time(self, client): await client.datetime.get_local_negative_offset_min_date_time() await client.datetime.put_local_negative_offset_min_date_time( - isodate.parse_datetime("0001-01-01T00:00:00-14:00")) + isodate.parse_datetime("0001-01-01T00:00:00-14:00") + ) @pytest.mark.asyncio async def test_get_local_no_offset_min_date_time(self, client): @@ -102,14 +105,16 @@ async def test_local_positive_offset_min_date_time(self, client): with pytest.raises(SerializationError): await client.datetime.put_local_positive_offset_min_date_time( - isodate.parse_datetime("0001-01-01T00:00:00+14:00")) + isodate.parse_datetime("0001-01-01T00:00:00+14:00") + ) @pytest.mark.asyncio async def test_local_positive_offset_max_date_time(self, client): await client.datetime.get_local_positive_offset_lowercase_max_date_time() await client.datetime.get_local_positive_offset_uppercase_max_date_time() await client.datetime.put_local_positive_offset_max_date_time( - isodate.parse_datetime("9999-12-31T23:59:59.999999+14:00")) + isodate.parse_datetime("9999-12-31T23:59:59.999999+14:00") + ) @pytest.mark.asyncio async def test_get_null(self, client): @@ -134,4 +139,5 @@ async def test_get_underflow(self, client): async def test_put_local_negative_offset_max_date_time(self, client): with pytest.raises(SerializationError): await client.datetime.put_local_negative_offset_max_date_time( - isodate.parse_datetime("9999-12-31T23:59:59.999999-14:00")) + isodate.parse_datetime("9999-12-31T23:59:59.999999-14:00") + ) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime_rfc.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime_rfc.py index e7f20157d17..c04d34f050e 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime_rfc.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_datetime_rfc.py @@ -41,12 +41,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestRFC1123DateTimeTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestDateTimeRfc(object): @pytest.mark.asyncio diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_dictionary.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_dictionary.py index 68d63e05273..21fbb2d50ed 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_dictionary.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_dictionary.py @@ -34,7 +34,7 @@ from os.path import dirname, pardir, join, realpath cwd = dirname(realpath(__file__)) -log_level = int(os.environ.get('PythonLogLevel', 30)) +log_level = int(os.environ.get("PythonLogLevel", 30)) tests = realpath(join(cwd, pardir, "Expected", "AcceptanceTests")) sys.path.append(join(tests, "BodyDictionary")) @@ -46,18 +46,21 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATDictionaryService(base_url="http://localhost:3000") as client: await yield_(client) + @pytest.fixture def test_dict(): test_product1 = Widget(integer=1, string="2") test_product2 = Widget(integer=3, string="4") test_product3 = Widget(integer=5, string="6") - return {"0":test_product1, "1":test_product2, "2":test_product3} + return {"0": test_product1, "1": test_product2, "2": test_product3} + class TestDictionary(object): @@ -65,111 +68,109 @@ class TestDictionary(object): @pytest.mark.asyncio async def test_boolean_tfft(self, client): - tfft = {"0":True, "1":False, "2":False, "3":True} - assert tfft == (await client.dictionary.get_boolean_tfft()) + tfft = {"0": True, "1": False, "2": False, "3": True} + assert tfft == (await client.dictionary.get_boolean_tfft()) await client.dictionary.put_boolean_tfft(tfft) @pytest.mark.asyncio async def test_get_boolean_invalid(self, client): - invalid_null_dict = {"0":True, "1":None, "2":False} - assert invalid_null_dict == (await client.dictionary.get_boolean_invalid_null()) + invalid_null_dict = {"0": True, "1": None, "2": False} + assert invalid_null_dict == (await client.dictionary.get_boolean_invalid_null()) with pytest.raises(DeserializationError): await client.dictionary.get_boolean_invalid_string() @pytest.mark.asyncio async def test_integer_valid(self, client): - int_valid = {"0":1, "1":-1, "2":3, "3":300} - assert int_valid == (await client.dictionary.get_integer_valid()) + int_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert int_valid == (await client.dictionary.get_integer_valid()) await client.dictionary.put_integer_valid(int_valid) @pytest.mark.asyncio async def test_get_int_invalid(self, client): - int_null_dict = {"0":1, "1":None, "2":0} - assert int_null_dict == (await client.dictionary.get_int_invalid_null()) + int_null_dict = {"0": 1, "1": None, "2": 0} + assert int_null_dict == (await client.dictionary.get_int_invalid_null()) with pytest.raises(DeserializationError): await client.dictionary.get_int_invalid_string() @pytest.mark.asyncio async def test_long_valid(self, client): - long_valid = {"0":1, "1":-1, "2":3, "3":300} - assert long_valid == (await client.dictionary.get_long_valid()) + long_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert long_valid == (await client.dictionary.get_long_valid()) await client.dictionary.put_long_valid(long_valid) @pytest.mark.asyncio async def test_get_long_invalid(self, client): - long_null_dict = {"0":1, "1":None, "2":0} - assert long_null_dict == (await client.dictionary.get_long_invalid_null()) + long_null_dict = {"0": 1, "1": None, "2": 0} + assert long_null_dict == (await client.dictionary.get_long_invalid_null()) with pytest.raises(DeserializationError): await client.dictionary.get_long_invalid_string() @pytest.mark.asyncio async def test_float_valid(self, client): - float_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert float_valid == (await client.dictionary.get_float_valid()) + float_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert float_valid == (await client.dictionary.get_float_valid()) await client.dictionary.put_float_valid(float_valid) @pytest.mark.asyncio async def test_get_float_invalid(self, client): - float_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert float_null_dict == (await client.dictionary.get_float_invalid_null()) + float_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert float_null_dict == (await client.dictionary.get_float_invalid_null()) with pytest.raises(DeserializationError): await client.dictionary.get_float_invalid_string() @pytest.mark.asyncio async def test_double_valid(self, client): - double_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert double_valid == (await client.dictionary.get_double_valid()) + double_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert double_valid == (await client.dictionary.get_double_valid()) await client.dictionary.put_double_valid(double_valid) @pytest.mark.asyncio async def test_get_double_invalid(self, client): - double_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert double_null_dict == (await client.dictionary.get_double_invalid_null()) + double_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert double_null_dict == (await client.dictionary.get_double_invalid_null()) with pytest.raises(DeserializationError): await client.dictionary.get_double_invalid_string() @pytest.mark.asyncio async def test_string_valid(self, client): - string_valid = {"0":"foo1", "1":"foo2", "2":"foo3"} - assert string_valid == (await client.dictionary.get_string_valid()) + string_valid = {"0": "foo1", "1": "foo2", "2": "foo3"} + assert string_valid == (await client.dictionary.get_string_valid()) await client.dictionary.put_string_valid(string_valid) @pytest.mark.asyncio async def test_get_string_with_null_and_invalid(self, client): - string_null_dict = {"0":"foo", "1":None, "2":"foo2"} - string_invalid_dict = {"0":"foo", "1":"123", "2":"foo2"} - assert string_null_dict == (await client.dictionary.get_string_with_null()) - assert string_invalid_dict == (await client.dictionary.get_string_with_invalid()) + string_null_dict = {"0": "foo", "1": None, "2": "foo2"} + string_invalid_dict = {"0": "foo", "1": "123", "2": "foo2"} + assert string_null_dict == (await client.dictionary.get_string_with_null()) + assert string_invalid_dict == (await client.dictionary.get_string_with_invalid()) @pytest.mark.asyncio async def test_date_valid(self, client): date1 = isodate.parse_date("2000-12-01T00:00:00Z") date2 = isodate.parse_date("1980-01-02T00:00:00Z") date3 = isodate.parse_date("1492-10-12T00:00:00Z") - valid_date_dict = {"0":date1, "1":date2, "2":date3} + valid_date_dict = {"0": date1, "1": date2, "2": date3} date_dictionary = await client.dictionary.get_date_valid() - assert date_dictionary == valid_date_dict + assert date_dictionary == valid_date_dict await client.dictionary.put_date_valid(valid_date_dict) @pytest.mark.asyncio async def test_get_date_invalid(self, client): - date_null_dict = {"0":isodate.parse_date("2012-01-01"), - "1":None, - "2":isodate.parse_date("1776-07-04")} - assert date_null_dict == await (client.dictionary.get_date_invalid_null()) + date_null_dict = {"0": isodate.parse_date("2012-01-01"), "1": None, "2": isodate.parse_date("1776-07-04")} + assert date_null_dict == await client.dictionary.get_date_invalid_null() with pytest.raises(DeserializationError): await client.dictionary.get_date_invalid_chars() @@ -179,16 +180,16 @@ async def test_date_time_valid(self, client): datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") datetime2 = isodate.parse_datetime("1980-01-02T00:11:35+01:00") datetime3 = isodate.parse_datetime("1492-10-12T10:15:01-08:00") - valid_datetime_dict = {"0":datetime1, "1":datetime2, "2":datetime3} + valid_datetime_dict = {"0": datetime1, "1": datetime2, "2": datetime3} - assert valid_datetime_dict == (await client.dictionary.get_date_time_valid()) + assert valid_datetime_dict == (await client.dictionary.get_date_time_valid()) await client.dictionary.put_date_time_valid(valid_datetime_dict) @pytest.mark.asyncio async def test_get_date_time_invalid(self, client): - datetime_null_dict = {"0":isodate.parse_datetime("2000-12-01T00:00:01Z"), "1":None} - assert datetime_null_dict == (await client.dictionary.get_date_time_invalid_null()) + datetime_null_dict = {"0": isodate.parse_datetime("2000-12-01T00:00:01Z"), "1": None} + assert datetime_null_dict == (await client.dictionary.get_date_time_invalid_null()) with pytest.raises(DeserializationError): await client.dictionary.get_date_time_invalid_chars() @@ -198,9 +199,9 @@ async def test_date_time_rfc1123_valid(self, client): rfc_datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") rfc_datetime2 = isodate.parse_datetime("1980-01-02T00:11:35Z") rfc_datetime3 = isodate.parse_datetime("1492-10-12T10:15:01Z") - valid_rfc_dict = {"0":rfc_datetime1, "1":rfc_datetime2, "2":rfc_datetime3} + valid_rfc_dict = {"0": rfc_datetime1, "1": rfc_datetime2, "2": rfc_datetime3} - assert valid_rfc_dict == (await client.dictionary.get_date_time_rfc1123_valid()) + assert valid_rfc_dict == (await client.dictionary.get_date_time_rfc1123_valid()) await client.dictionary.put_date_time_rfc1123_valid(valid_rfc_dict) @@ -208,9 +209,9 @@ async def test_date_time_rfc1123_valid(self, client): async def test_get_duration_valid(self, client): duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration2 = timedelta(days=5, hours=1) - valid_duration_dict = {"0":duration1, "1":duration2} + valid_duration_dict = {"0": duration1, "1": duration2} - assert valid_duration_dict == (await client.dictionary.get_duration_valid()) + assert valid_duration_dict == (await client.dictionary.get_duration_valid()) await client.dictionary.put_duration_valid(valid_duration_dict) @@ -221,32 +222,34 @@ async def test_bytes_valid(self, client): bytes3 = bytearray([0x025, 0x029, 0x043]) bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_valid = {"0":bytes1, "1":bytes2, "2":bytes3} + bytes_valid = {"0": bytes1, "1": bytes2, "2": bytes3} await client.dictionary.put_byte_valid(bytes_valid) bytes_result = await client.dictionary.get_byte_valid() - assert bytes_valid == bytes_result + assert bytes_valid == bytes_result @pytest.mark.asyncio async def test_get_byte_invalid_null(self, client): bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_null = {"0":bytes4, "1":None} + bytes_null = {"0": bytes4, "1": None} bytes_result = await client.dictionary.get_byte_invalid_null() - assert bytes_null == bytes_result + assert bytes_null == bytes_result @pytest.mark.asyncio async def test_get_base64_url(self, client): - test_dict = {'0': 'a string that gets encoded with base64url'.encode(), - '1': 'test string'.encode(), - '2': 'Lorem ipsum'.encode()} - assert (await client.dictionary.get_base64_url())== test_dict + test_dict = { + "0": "a string that gets encoded with base64url".encode(), + "1": "test string".encode(), + "2": "Lorem ipsum".encode(), + } + assert (await client.dictionary.get_base64_url()) == test_dict # Basic dictionary parsing @pytest.mark.asyncio async def test_empty(self, client): - assert {} == (await client.dictionary.get_empty()) + assert {} == (await client.dictionary.get_empty()) await client.dictionary.put_empty({}) @@ -263,89 +266,95 @@ async def test_get_null_key_and_value(self, client): # but we fail and we're happy with it. with pytest.raises(DecodeError): await client.dictionary.get_null_key() - assert {"key1":None} == (await client.dictionary.get_null_value()) + assert {"key1": None} == (await client.dictionary.get_null_value()) @pytest.mark.asyncio async def test_get_empty_string_key(self, client): - assert {"":"val1"} == (await client.dictionary.get_empty_string_key()) + assert {"": "val1"} == (await client.dictionary.get_empty_string_key()) # Dictionary composed types @pytest.mark.asyncio async def test_get_complex_null_and_empty(self, client): assert await client.dictionary.get_complex_null() is None - assert {} == (await client.dictionary.get_complex_empty()) + assert {} == (await client.dictionary.get_complex_empty()) @pytest.mark.asyncio async def test_complex_valid(self, client, test_dict): await client.dictionary.put_complex_valid(test_dict) complex_result = await client.dictionary.get_complex_valid() - assert test_dict == complex_result + assert test_dict == complex_result @pytest.mark.asyncio async def test_array_valid(self, client): - list_dict = {"0":["1","2","3"], "1":["4","5","6"], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", "9"]} await client.dictionary.put_array_valid(list_dict) array_result = await client.dictionary.get_array_valid() - assert list_dict == array_result + assert list_dict == array_result @pytest.mark.asyncio async def test_dictionary_valid(self, client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{"4":"four","5":"five","6":"six"}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": {"4": "four", "5": "five", "6": "six"}, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } await client.dictionary.put_dictionary_valid(dict_dict) dict_result = await client.dictionary.get_dictionary_valid() - assert dict_dict == dict_result + assert dict_dict == dict_result @pytest.mark.asyncio async def test_get_complex_null_and_empty(self, client): assert await client.dictionary.get_complex_null() is None - assert {} == (await client.dictionary.get_complex_empty()) + assert {} == (await client.dictionary.get_complex_empty()) @pytest.mark.asyncio async def test_get_complex_item_null_and_empty(self, client, test_dict): - test_dict_null = {"0":test_dict["0"], "1":None, "2":test_dict["2"]} + test_dict_null = {"0": test_dict["0"], "1": None, "2": test_dict["2"]} complex_result = await client.dictionary.get_complex_item_null() - assert complex_result == test_dict_null + assert complex_result == test_dict_null - test_dict_empty = {"0":test_dict["0"], "1":Widget(), "2":test_dict["2"]} + test_dict_empty = {"0": test_dict["0"], "1": Widget(), "2": test_dict["2"]} complex_result = await client.dictionary.get_complex_item_empty() - assert complex_result == test_dict_empty + assert complex_result == test_dict_empty @pytest.mark.asyncio async def test_get_array_empty(self, client): assert await client.dictionary.get_array_null() is None - assert {} == (await client.dictionary.get_array_empty()) + assert {} == (await client.dictionary.get_array_empty()) @pytest.mark.asyncio async def test_get_array_item_null_and_empty(self, client): - list_dict = {"0":["1","2","3"], "1":None, "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": None, "2": ["7", "8", "9"]} array_result = await client.dictionary.get_array_item_null() - assert list_dict == array_result + assert list_dict == array_result - list_dict = {"0":["1","2","3"], "1":[], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": [], "2": ["7", "8", "9"]} array_result = await client.dictionary.get_array_item_empty() - assert list_dict == array_result + assert list_dict == array_result @pytest.mark.asyncio async def test_get_dictionary_null_and_empty(self, client): assert await client.dictionary.get_dictionary_null() is None - assert {} == (await client.dictionary.get_dictionary_empty()) + assert {} == (await client.dictionary.get_dictionary_empty()) @pytest.mark.asyncio async def test_get_dictionary_item_null_and_empty(self, client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":None, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": None, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } dict_result = await client.dictionary.get_dictionary_item_null() - assert dict_dict == dict_result + assert dict_dict == dict_result - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": {}, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } dict_result = await client.dictionary.get_dictionary_item_empty() - assert dict_dict == dict_result + assert dict_dict == dict_result diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_duration.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_duration.py index 82407864b23..c92153264d5 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_duration.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_duration.py @@ -41,12 +41,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDurationTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestDuration(object): @pytest.mark.asyncio @@ -59,4 +61,6 @@ async def test_get_null_and_invalid(self, client): @pytest.mark.asyncio async def test_positive_duration(self, client): await client.duration.get_positive_duration() - await client.duration.put_positive_duration(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) + await client.duration.put_positive_duration( + timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) + ) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_error_with_secrets.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_error_with_secrets.py index be7496804d9..9bc40f0e614 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_error_with_secrets.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_error_with_secrets.py @@ -28,21 +28,24 @@ from errorwithsecrets.aio import ErrorWithSecrets from azure.core.exceptions import HttpResponseError + @pytest.fixture async def client(): async with ErrorWithSecrets() as client: yield client + @pytest.mark.asyncio async def test_create_secret(client): request = build_create_secret_request( headers={"authorization": "SharedKey 1c88a67921784300a462b2cb61da2339"}, params={"key": "1c88a67921784300a462b2cb61da2339"}, - json={ "key": "1c88a67921784300a462b2cb61da2339" }, + json={"key": "1c88a67921784300a462b2cb61da2339"}, ) response = await client._send_request(request) response.raise_for_status() + @pytest.mark.asyncio async def test_raise_error_with_secrets(client): with pytest.raises(HttpResponseError) as ex: diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_extensible_enums.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_extensible_enums.py index d92391f901b..9058e73b5da 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_extensible_enums.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_extensible_enums.py @@ -40,40 +40,38 @@ import pytest + @pytest.fixture @async_generator async def client(): async with PetStoreInc(base_url="http://localhost:3000") as client: await yield_(client) + class TestExtensibleEnums(object): @pytest.mark.asyncio async def test_get_by_pet_id(self, client): # Now enum return are always string (Autorest.Python 3.0) - tommy = await client.pet.get_by_pet_id('tommy') - assert tommy.days_of_week == "Monday" - assert tommy.int_enum == "1" + tommy = await client.pet.get_by_pet_id("tommy") + assert tommy.days_of_week == "Monday" + assert tommy.int_enum == "1" - casper = await client.pet.get_by_pet_id('casper') - assert casper.days_of_week == "Weekend" - assert casper.int_enum == "2" + casper = await client.pet.get_by_pet_id("casper") + assert casper.days_of_week == "Weekend" + assert casper.int_enum == "2" - scooby = await client.pet.get_by_pet_id('scooby') - assert scooby.days_of_week == "Thursday" + scooby = await client.pet.get_by_pet_id("scooby") + assert scooby.days_of_week == "Thursday" # https://github.com/Azure/autorest.csharp/blob/e5f871b7433e0f6ca6a17307fba4a2cfea4942b4/test/vanilla/AcceptanceTests.cs#L429 # "allowedValues" of "x-ms-enum" is not supported in Python - assert scooby.int_enum == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" + assert scooby.int_enum == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" @pytest.mark.asyncio async def test_add_pet(self, client): - retriever = Pet( - name="Retriever", - int_enum=IntEnum.three, - days_of_week=DaysOfWeekExtensibleEnum.friday - ) + retriever = Pet(name="Retriever", int_enum=IntEnum.three, days_of_week=DaysOfWeekExtensibleEnum.friday) returned_pet = await client.pet.add_pet(retriever) - assert returned_pet.days_of_week == "Friday" - assert returned_pet.int_enum == "3" - assert returned_pet.name == "Retriever" \ No newline at end of file + assert returned_pet.days_of_week == "Friday" + assert returned_pet.int_enum == "3" + assert returned_pet.name == "Retriever" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_file.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_file.py index aa9316b6e75..0e7ee52d8ec 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_file.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_file.py @@ -50,16 +50,19 @@ async def client(connection_data_block_size=None): ) as client: await yield_(client) + @pytest.fixture def callback(): def _callback(response, data_stream, headers): assert not data_stream.response.internal_response._released return data_stream + return _callback + class TestFile(object): @pytest.mark.asyncio - @pytest.mark.parametrize('client', [1000], indirect=True) + @pytest.mark.parametrize("client", [1000], indirect=True) async def test_get_file(self, client): file_length = 0 with io.BytesIO() as file_handle: @@ -70,21 +73,33 @@ async def test_get_file(self, client): async for data in stream: assert 0 < len(data) <= stream.block_size file_length += len(data) - print("Downloading... {}%".format(int(file_length*100/total))) + print("Downloading... {}%".format(int(file_length * 100 / total))) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) - - with open(sample_file, 'rb') as data: + join( + cwd, + pardir, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) + + with open(sample_file, "rb") as data: sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) + assert sample_data == hash(file_handle.getvalue()) @pytest.mark.asyncio - @pytest.mark.parametrize('client', [4096], indirect=True) + @pytest.mark.parametrize("client", [4096], indirect=True) async def test_get_empty_file(self, client): file_length = 0 with io.BytesIO() as file_handle: @@ -96,10 +111,10 @@ async def test_get_empty_file(self, client): file_length += len(data) file_handle.write(data) - assert file_length == 0 + assert file_length == 0 @pytest.mark.asyncio - @pytest.mark.parametrize('client', [4096], indirect=True) + @pytest.mark.parametrize("client", [4096], indirect=True) async def test_files_long_running(self, client): file_length = 0 stream = await client.files.get_file_large() @@ -107,10 +122,10 @@ async def test_files_long_running(self, client): assert 0 < len(data) <= stream.block_size file_length += len(data) - assert file_length == 3000 * 1024 * 1024 + assert file_length == 3000 * 1024 * 1024 @pytest.mark.asyncio - @pytest.mark.parametrize('client', [None], indirect=True) + @pytest.mark.parametrize("client", [None], indirect=True) async def test_get_file_with_callback(self, client, callback): file_length = 0 with io.BytesIO() as file_handle: @@ -121,18 +136,30 @@ async def test_get_file_with_callback(self, client, callback): file_length += len(data) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) - - with open(sample_file, 'rb') as data: + join( + cwd, + pardir, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) + + with open(sample_file, "rb") as data: sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) + assert sample_data == hash(file_handle.getvalue()) @pytest.mark.asyncio - @pytest.mark.parametrize('client', [None], indirect=True) + @pytest.mark.parametrize("client", [None], indirect=True) async def test_get_empty_file_with_callback(self, client, callback): file_length = 0 with io.BytesIO() as file_handle: @@ -142,4 +169,4 @@ async def test_get_empty_file_with_callback(self, client, callback): file_handle.write(data) assert stream.response.internal_response._released - assert file_length == 0 + assert file_length == 0 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_form_data.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_form_data.py index 79b4e643a96..26ffa629c86 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_form_data.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_form_data.py @@ -37,22 +37,24 @@ import pytest + @pytest.fixture def dummy_file(): - with tempfile.NamedTemporaryFile(mode='w', delete=False) as dummy: + with tempfile.NamedTemporaryFile(mode="w", delete=False) as dummy: dummy.write("Test file") # Get outside of the "with", so file can be re-opened on Windows yield dummy.name os.remove(dummy.name) + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATFormDataService( base_url="http://localhost:3000", - connection_data_block_size = 2, - retry_total = 50, # Be agressive on this test, sometimes testserver DDOS :-p - retry_backoff_factor = 1.6 + connection_data_block_size=2, + retry_total=50, # Be agressive on this test, sometimes testserver DDOS :-p + retry_backoff_factor=1.6, ) as client: await yield_(client) @@ -62,13 +64,13 @@ class TestFormData(object): @pytest.mark.asyncio async def test_file_upload_stream(self, client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = await client.formdata.upload_file(stream_data, "UploadFile.txt") async for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string @pytest.mark.asyncio async def test_file_upload_stream_raw(self, client): @@ -76,23 +78,23 @@ def test_callback(response, data, headers): return data test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = await client.formdata.upload_file(stream_data, "UploadFile.txt", cls=test_callback) async for data in resp: result.write(data) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string @pytest.mark.asyncio async def test_file_upload_file_stream(self, client, dummy_file): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = await client.formdata.upload_file(upload_data, name) async for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" @pytest.mark.asyncio async def test_file_upload_file_stream_raw(self, client, dummy_file): @@ -102,35 +104,35 @@ def test_callback(response, data, headers): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = await client.formdata.upload_file(upload_data, name, cls=test_callback) async for data in resp: result.write(data) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" @pytest.mark.asyncio async def test_file_body_upload(self, client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = await client.formdata.upload_file_via_body(stream_data) async for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = await client.formdata.upload_file_via_body(upload_data) async for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" @pytest.mark.asyncio async def test_file_body_upload_generator(self, client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") @async_generator async def stream_upload(data, length, block_size): @@ -138,7 +140,7 @@ async def stream_upload(data, length, block_size): while True: block = data.read(block_size) progress += len(block) - print("Progress... {}%".format(int(progress*100/length))) + print("Progress... {}%".format(int(progress * 100 / length))) if not block: break await yield_(block) @@ -149,12 +151,12 @@ async def stream_upload(data, length, block_size): resp = await client.formdata.upload_file_via_body(streamed_upload) async for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: streamed_upload = stream_upload(upload_data, len("Test file"), 2) response = await client.formdata.upload_file_via_body(streamed_upload) async for data in response: result.write(data) - assert result.getvalue().decode() == "Test file" \ No newline at end of file + assert result.getvalue().decode() == "Test file" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_header.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_header.py index 4e025c16768..fcdb13e4ce3 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_header.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_header.py @@ -42,18 +42,22 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATHeaderService(base_url="http://localhost:3000") as client: await yield_(client) + @pytest.fixture def value_header(): def _value_header(response, _, headers): return headers.get("value") + return _value_header + class TestHeader(object): @pytest.mark.asyncio @@ -123,7 +127,7 @@ async def test_string(self, client, value_header): @pytest.mark.asyncio async def test_enum(self, client, value_header): await client.header.param_enum("valid", GreyscaleColors.grey) - await client.header.param_enum("valid", 'GREY') + await client.header.param_enum("valid", "GREY") await client.header.param_enum("null", None) response = await client.header.response_enum("valid", cls=value_header) @@ -172,14 +176,16 @@ async def test_datetime_rfc(self, client, value_header): @pytest.mark.asyncio async def test_duration(self, client, value_header): - await client.header.param_duration("valid", timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) + await client.header.param_duration( + "valid", timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) + ) response = await client.header.response_duration("valid", cls=value_header) assert response == timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) @pytest.mark.asyncio async def test_byte(self, client, value_header): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") await client.header.param_byte("valid", u_bytes) response = await client.header.response_byte("valid", cls=value_header) @@ -190,18 +196,20 @@ async def test_byte(self, client, value_header): @pytest.mark.asyncio async def test_response_existing_key(self, client): def useragent_header(response, _, headers): - return headers.get('User-Agent') + return headers.get("User-Agent") + response = await client.header.response_existing_key(cls=useragent_header) assert response == "overwrite" @pytest.mark.asyncio async def test_response_protected_key(self, client): # This test is only valid for C#, which content-type can't be override this way - #await client.header.param_protected_key("text/html") + # await client.header.param_protected_key("text/html") # This test has different result compare to C#, which content-type is saved in another place. def content_header(response, _, headers): - return headers.get('Content-Type') + return headers.get("Content-Type") + response = await client.header.response_protected_key(cls=content_header) assert response == "text/html; charset=utf-8" @@ -209,6 +217,7 @@ def content_header(response, _, headers): async def test_custom_request_id(self, client): def status_code(pipeline_response, _, headers): return pipeline_response.http_response.status_code + custom_headers = {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} response = await client.header.custom_request_id(headers=custom_headers, cls=status_code) assert response == 200 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_hooks.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_hooks.py index 25b16f52e90..5c6450501ad 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_hooks.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_hooks.py @@ -27,27 +27,32 @@ from azure.core.pipeline.policies import CustomHookPolicy from bodyarray.aio import AutoRestSwaggerBATArrayService + def is_rest(obj): return hasattr(obj, "content") + @pytest.mark.asyncio async def test_raw_request_hook(): def _callback(request): assert not is_rest(request.http_request) assert hasattr(request.http_request, "set_multipart_mixed") raise ValueError("I entered the callback!") + raw_request_hook_policy = CustomHookPolicy(raw_request_hook=_callback) async with AutoRestSwaggerBATArrayService(policies=[raw_request_hook_policy]) as client: with pytest.raises(ValueError) as ex: await client.array.get_array_empty() assert "I entered the callback!" in str(ex.value) + @pytest.mark.asyncio async def test_raw_response_hook(): def _callback(response): assert not is_rest(response.http_response) assert hasattr(response.http_response, "parts") raise ValueError("I entered the callback!") + raw_response_hook_policy = CustomHookPolicy(raw_response_hook=_callback) async with AutoRestSwaggerBATArrayService(policies=[raw_response_hook_policy]) as client: with pytest.raises(ValueError) as ex: diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_http.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_http.py index 7a5edb8886a..b7046c28ad1 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_http.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_http.py @@ -50,13 +50,7 @@ @async_generator async def client(cookie_policy): """Create a AutoRestHttpInfrastructureTestService client with test server credentials.""" - policies = [ - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRedirectPolicy(), - AsyncRetryPolicy(), - cookie_policy - ] + policies = [HeadersPolicy(), ContentDecodePolicy(), AsyncRedirectPolicy(), AsyncRetryPolicy(), cookie_policy] async with AutoRestHttpInfrastructureTestService(base_url="http://localhost:3000", policies=policies) as client: await yield_(client) @@ -65,7 +59,8 @@ class TestHttp(object): async def assert_status(self, code, func, *args, **kwargs): def return_status(pipeline_response, data, headers): return pipeline_response.http_response.status_code - kwargs['cls'] = return_status + + kwargs["cls"] = return_status status_code = await func(*args, **kwargs) assert status_code == code @@ -115,22 +110,24 @@ async def assert_raises_with_status_and_response_contains(self, code, msg, func, assert err.response.status_code == code assert msg in err.response.text() - @pytest.mark.asyncio async def test_get200_model204(self, client): r = await client.multiple_responses.get200_model204_no_model_default_error200_valid() - assert '200' == r.status_code + assert "200" == r.status_code - await self.assert_raises_with_status(201, - client.multiple_responses.get200_model204_no_model_default_error201_invalid) + await self.assert_raises_with_status( + 201, client.multiple_responses.get200_model204_no_model_default_error201_invalid + ) - await self.assert_raises_with_status(202, - client.multiple_responses.get200_model204_no_model_default_error202_none) + await self.assert_raises_with_status( + 202, client.multiple_responses.get200_model204_no_model_default_error202_none + ) assert (await client.multiple_responses.get200_model204_no_model_default_error204_valid()) is None - await self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model204_no_model_default_error400_valid) + await self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model204_no_model_default_error400_valid + ) @pytest.mark.asyncio async def test_get200_model201(self, client): @@ -138,45 +135,46 @@ async def test_get200_model201(self, client): b_model = await client.multiple_responses.get200_model201_model_default_error201_valid() assert b_model is not None - assert b_model.status_code == "201" - assert b_model.text_status_code == "Created" + assert b_model.status_code == "201" + assert b_model.text_status_code == "Created" - await self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model201_model_default_error400_valid) + await self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model201_model_default_error400_valid + ) @pytest.mark.asyncio async def test_get200_model_a201_model_c404(self, client): a_model = await client.multiple_responses.get200_model_a201_model_c404_model_d_default_error200_valid() assert a_model is not None - assert a_model.status_code == "200" + assert a_model.status_code == "200" c_model = await client.multiple_responses.get200_model_a201_model_c404_model_d_default_error201_valid() assert c_model is not None - assert c_model.http_code == "201" + assert c_model.http_code == "201" d_model = await client.multiple_responses.get200_model_a201_model_c404_model_d_default_error404_valid() assert d_model is not None - assert d_model.http_status_code == "404" + assert d_model.http_status_code == "404" - await self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid) + await self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid + ) @pytest.mark.asyncio async def test_get202_none204(self, client): await client.multiple_responses.get202_none204_none_default_error202_none() await client.multiple_responses.get202_none204_none_default_error204_none() - await self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get202_none204_none_default_error400_valid) + await self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get202_none204_none_default_error400_valid + ) await client.multiple_responses.get202_none204_none_default_none202_invalid() await client.multiple_responses.get202_none204_none_default_none204_none() - await self.assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_none) + await self.assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_none) - await self.assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_invalid) + await self.assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_invalid) @pytest.mark.asyncio async def test_get_default_model_a200(self, client): @@ -188,11 +186,9 @@ async def test_get_default_model_a200(self, client): @pytest.mark.asyncio async def test_get_default_model_a400(self, client): - await self.assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_valid) + await self.assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_valid) - await self.assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_none) + await self.assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_none) @pytest.mark.asyncio async def test_get_default_none200(self, client): @@ -201,11 +197,9 @@ async def test_get_default_none200(self, client): @pytest.mark.asyncio async def test_get_default_none400(self, client): - await self.assert_raises_with_status(400, - client.multiple_responses.get_default_none400_invalid) + await self.assert_raises_with_status(400, client.multiple_responses.get_default_none400_invalid) - await self.assert_raises_with_status(400, - client.multiple_responses.get_default_none400_none) + await self.assert_raises_with_status(400, client.multiple_responses.get_default_none400_none) @pytest.mark.asyncio async def test_get200_model_a200(self, client): @@ -217,34 +211,30 @@ async def test_get200_model_a200(self, client): @pytest.mark.asyncio async def test_get200_model_a400(self, client): - await self.assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_none) - await self.assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_valid) - await self.assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_invalid) + await self.assert_raises_with_status(400, client.multiple_responses.get200_model_a400_none) + await self.assert_raises_with_status(400, client.multiple_responses.get200_model_a400_valid) + await self.assert_raises_with_status(400, client.multiple_responses.get200_model_a400_invalid) @pytest.mark.asyncio async def test_get200_model_a202(self, client): - await self.assert_raises_with_status(202, - client.multiple_responses.get200_model_a202_valid) + await self.assert_raises_with_status(202, client.multiple_responses.get200_model_a202_valid) @pytest.mark.asyncio async def test_server_error_status_codes_501(self, client): - await self.assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.head501) + await self.assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.head501) - await self.assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.get501) + await self.assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.get501) @pytest.mark.asyncio async def test_server_error_status_codes_505(self, client): - await self.assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.post505) + await self.assert_raises_with_status( + requests.codes.http_version_not_supported, client.http_server_failure.post505 + ) - await self.assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.delete505) + await self.assert_raises_with_status( + requests.codes.http_version_not_supported, client.http_server_failure.delete505 + ) @pytest.mark.asyncio async def test_retry_status_codes_408(self, client): @@ -272,106 +262,87 @@ async def test_retry_status_codes_504(self, client): @pytest.mark.asyncio async def test_error_status_codes_400(self, client): - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.head400) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.head400) - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.get400) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.get400) # TODO, 4042586: Support options operations in swagger modeler - #await self.assert_raises_with_status(requests.codes.bad_request, + # await self.assert_raises_with_status(requests.codes.bad_request, # await client.http_client_failure.options400) - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.put400) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.put400) - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.patch400) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.patch400) - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.post400) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.post400) - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.delete400) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.delete400) @pytest.mark.asyncio async def test_error_status_codes_401(self, client): - await self.assert_raises_with_status(requests.codes.unauthorized, - client.http_client_failure.head401) + await self.assert_raises_with_status(requests.codes.unauthorized, client.http_client_failure.head401) @pytest.mark.asyncio async def test_error_status_codes_402(self, client): - await self.assert_raises_with_status(requests.codes.payment_required, - client.http_client_failure.get402) + await self.assert_raises_with_status(requests.codes.payment_required, client.http_client_failure.get402) @pytest.mark.asyncio async def test_error_status_codes_403(self, client): # TODO, 4042586: Support options operations in swagger modeler - #await self.assert_raises_with_status(requests.codes.forbidden, + # await self.assert_raises_with_status(requests.codes.forbidden, # client.http_client_failure.options403) - await self.assert_raises_with_status(requests.codes.forbidden, - client.http_client_failure.get403) + await self.assert_raises_with_status(requests.codes.forbidden, client.http_client_failure.get403) @pytest.mark.asyncio async def test_error_status_codes_404(self, client): - await self.assert_raises_with_status(requests.codes.not_found, - client.http_client_failure.put404) + await self.assert_raises_with_status(requests.codes.not_found, client.http_client_failure.put404) @pytest.mark.asyncio async def test_error_status_codes_405(self, client): - await self.assert_raises_with_status(requests.codes.method_not_allowed, - client.http_client_failure.patch405) + await self.assert_raises_with_status(requests.codes.method_not_allowed, client.http_client_failure.patch405) @pytest.mark.asyncio async def test_error_status_codes_406(self, client): - await self.assert_raises_with_status(requests.codes.not_acceptable, - client.http_client_failure.post406) + await self.assert_raises_with_status(requests.codes.not_acceptable, client.http_client_failure.post406) @pytest.mark.asyncio async def test_error_status_codes_407(self, client): - await self.assert_raises_with_status(requests.codes.proxy_authentication_required, - client.http_client_failure.delete407) + await self.assert_raises_with_status( + requests.codes.proxy_authentication_required, client.http_client_failure.delete407 + ) @pytest.mark.asyncio async def test_error_status_codes_409(self, client): - await self.assert_raises_with_status(requests.codes.conflict, - client.http_client_failure.put409) + await self.assert_raises_with_status(requests.codes.conflict, client.http_client_failure.put409) @pytest.mark.asyncio async def test_error_status_codes_410(self, client): - await self.assert_raises_with_status(requests.codes.gone, - client.http_client_failure.head410) + await self.assert_raises_with_status(requests.codes.gone, client.http_client_failure.head410) @pytest.mark.asyncio async def test_error_status_codes_411(self, client): - await self.assert_raises_with_status(requests.codes.length_required, - client.http_client_failure.get411) + await self.assert_raises_with_status(requests.codes.length_required, client.http_client_failure.get411) # TODO, 4042586: Support options operations in swagger modeler - #await self.assert_raises_with_status(requests.codes.precondition_failed, + # await self.assert_raises_with_status(requests.codes.precondition_failed, # client.http_client_failure.options412) - await self.assert_raises_with_status(requests.codes.precondition_failed, - client.http_client_failure.get412) + await self.assert_raises_with_status(requests.codes.precondition_failed, client.http_client_failure.get412) - await self.assert_raises_with_status(requests.codes.request_entity_too_large, - client.http_client_failure.put413) + await self.assert_raises_with_status(requests.codes.request_entity_too_large, client.http_client_failure.put413) - await self.assert_raises_with_status(requests.codes.request_uri_too_large, - client.http_client_failure.patch414) + await self.assert_raises_with_status(requests.codes.request_uri_too_large, client.http_client_failure.patch414) - await self.assert_raises_with_status(requests.codes.unsupported_media, - client.http_client_failure.post415) + await self.assert_raises_with_status(requests.codes.unsupported_media, client.http_client_failure.post415) - await self.assert_raises_with_status(requests.codes.requested_range_not_satisfiable, - client.http_client_failure.get416) + await self.assert_raises_with_status( + requests.codes.requested_range_not_satisfiable, client.http_client_failure.get416 + ) - await self.assert_raises_with_status(requests.codes.expectation_failed, - client.http_client_failure.delete417) + await self.assert_raises_with_status(requests.codes.expectation_failed, client.http_client_failure.delete417) - await self.assert_raises_with_status(429, - client.http_client_failure.head429) + await self.assert_raises_with_status(429, client.http_client_failure.head429) @pytest.mark.asyncio async def test_redirect_to_300(self, client): @@ -406,13 +377,15 @@ async def test_redirect_to_307(self, client): @pytest.mark.asyncio async def test_bad_request_status_assert(self, client): - await self.assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - (client.http_failure.get_empty_error)) + await self.assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", (client.http_failure.get_empty_error) + ) @pytest.mark.asyncio async def test_no_error_model_status_assert(self, client): - await self.assert_raises_with_status_and_response_contains(requests.codes.bad_request, "NoErrorModel", - (client.http_failure.get_no_model_error)) + await self.assert_raises_with_status_and_response_contains( + requests.codes.bad_request, "NoErrorModel", (client.http_failure.get_no_model_error) + ) @pytest.mark.asyncio async def test_success_status_codes_200(self, client): @@ -424,7 +397,7 @@ async def test_success_status_codes_200(self, client): await client.http_success.delete200() # TODO, 4042586: Support options operations in swagger modeler - #assert await client.http_success.options200() + # assert await client.http_success.options200() @pytest.mark.asyncio async def test_success_status_codes_201(self, client): @@ -452,5 +425,4 @@ async def test_success_status_codes_404(self, client): @pytest.mark.asyncio async def test_empty_no_content(self, client): - await self.assert_raises_with_status(requests.codes.bad_request, - client.http_failure.get_no_model_empty) + await self.assert_raises_with_status(requests.codes.bad_request, client.http_failure.get_no_model_empty) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_incorrect_error_response.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_incorrect_error_response.py index b9c39944480..4a6ffa35ebf 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_incorrect_error_response.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_incorrect_error_response.py @@ -27,8 +27,9 @@ from azure.core.exceptions import HttpResponseError from incorrecterrorresponse.aio import IncorrectReturnedErrorModel + @pytest.mark.asyncio async def test_swallow_deserialization_error_for_error_model(): client = IncorrectReturnedErrorModel(base_url="http://localhost:3000") with pytest.raises(HttpResponseError): - await client.get_incorrect_error_from_server() \ No newline at end of file + await client.get_incorrect_error_from_server() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_inputs.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_inputs.py index 815185dde79..011ec0542a4 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_inputs.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_inputs.py @@ -26,14 +26,17 @@ import pytest from bodycomplex.aio import AutoRestComplexTestService from azure.core.pipeline.policies import CustomHookPolicy + try: from urlparse import urlparse # type: ignore except ImportError: from urllib.parse import urlparse + def get_client(callback): return AutoRestComplexTestService(policies=[CustomHookPolicy(raw_request_hook=callback)]) + @pytest.mark.asyncio async def test_header_input(): def get_headers(pipeline_request): @@ -41,29 +44,34 @@ def get_headers(pipeline_request): assert pipeline_request.http_request.headers["hello"] == "world!" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: await client.basic.get_empty(headers={"hello": "world!"}) assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_header_input_override(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 1 assert pipeline_request.http_request.headers["Accept"] == "my/content-type" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: await client.basic.get_empty(headers={"Accept": "my/content-type"}) assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_header_none_input(): async with AutoRestComplexTestService() as client: await client.basic.get_empty(headers=None) + @pytest.mark.asyncio async def test_header_case_insensitive(): def get_headers(pipeline_request): @@ -79,29 +87,34 @@ def get_headers(pipeline_request): assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_header_kwarg_and_header(): def get_headers(pipeline_request): assert pipeline_request.http_request.headers["content-type"] == "my/json" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: await client.basic.put_valid({}, headers={"content-type": "shouldn't/be-me"}, content_type="my/json") assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_input(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "foo=bar" raise ValueError("Passed!") + client = get_client(callback=get_query) with pytest.raises(ValueError) as ex: await client.basic.get_empty(params={"foo": "bar"}) assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_input_override(): def get_query(pipeline_request): @@ -116,11 +129,13 @@ def get_query(pipeline_request): assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_none_input(): async with AutoRestComplexTestService() as client: await client.basic.get_empty(params=None) + @pytest.mark.asyncio async def test_query_case_insensitive(): def get_query(pipeline_request): @@ -135,6 +150,7 @@ def get_query(pipeline_request): assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_kwarg_and_header(): def get_query(pipeline_request): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_integer.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_integer.py index 2a537308075..fe4496a4e66 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_integer.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_integer.py @@ -41,16 +41,18 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestIntegerTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestInteger(object): @pytest.mark.asyncio async def test_max_min_32_bit(self, client): - await client.int_operations.put_max32(2147483647) # sys.maxint + await client.int_operations.put_max32(2147483647) # sys.maxint await client.int_operations.put_min32(-2147483648) @pytest.mark.asyncio @@ -80,7 +82,7 @@ async def test_get_underflow(self, client): async def test_unix_time_date(self, client): unix_date = datetime(year=2016, month=4, day=13) await client.int_operations.put_unix_time_date(unix_date) - assert unix_date.utctimetuple() == (await client.int_operations.get_unix_time()).utctimetuple() + assert unix_date.utctimetuple() == (await client.int_operations.get_unix_time()).utctimetuple() @pytest.mark.asyncio async def test_get_null_and_invalid_unix_time(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_media_types.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_media_types.py index 44404c6e370..2a0386e686d 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_media_types.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_media_types.py @@ -32,6 +32,7 @@ import pytest import json + @pytest.fixture @async_generator async def client(): @@ -53,7 +54,7 @@ async def test_json(self, client): @pytest.mark.asyncio async def test_content_type_with_encoding(self, client): - result = await client.content_type_with_encoding(input="hello", content_type='text/plain; charset=UTF-8') + result = await client.content_type_with_encoding(input="hello", content_type="text/plain; charset=UTF-8") assert result == "Nice job sending content type with encoding" @pytest.mark.asyncio @@ -67,7 +68,7 @@ async def test_json_no_accept_header(self, client): @pytest.mark.asyncio async def test_binary_body_two_content_types(self, client): - json_input = json.dumps({"hello":"world"}) + json_input = json.dumps({"hello": "world"}) await client.binary_body_with_two_content_types(json_input, content_type="application/json") content = b"hello, world" @@ -75,7 +76,7 @@ async def test_binary_body_two_content_types(self, client): @pytest.mark.asyncio async def test_binary_body_three_content_types(self, client): - json_input = json.dumps({"hello":"world"}) + json_input = json.dumps({"hello": "world"}) await client.binary_body_with_three_content_types(json_input) content = b"hello, world" @@ -86,7 +87,7 @@ async def test_binary_body_three_content_types(self, client): @pytest.mark.asyncio async def test_body_three_types(self, client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} await client.body_three_types(json_input) content = b"hello, world" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_merge_patch_json.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_merge_patch_json.py index 7c426d72fdd..829028de104 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_merge_patch_json.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_merge_patch_json.py @@ -27,11 +27,13 @@ import pytest + @pytest.fixture async def client(): async with MergePatchJsonClient() as client: yield client + @pytest.mark.asyncio async def test_merge_patch_json(client): await client.patch_single({"foo": "bar"}) == "Success!" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_model_flattening.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_model_flattening.py index 2cd28261de1..a1832217f89 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_model_flattening.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_model_flattening.py @@ -36,172 +36,164 @@ from os.path import dirname, pardir, join, realpath from modelflattening.aio import AutoRestResourceFlatteningTestService -from modelflattening.models import ( - FlattenedProduct, - ResourceCollection, - SimpleProduct) +from modelflattening.models import FlattenedProduct, ResourceCollection, SimpleProduct import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestResourceFlatteningTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestModelFlatteningTests(object): @pytest.mark.asyncio async def test_flattening_array(self, client): - #Array + # Array result = await client.get_array() - assert 3 == len(result) + assert 3 == len(result) # Resource 1 - assert "1" == result[0].id - assert "OK" == result[0].provisioning_state_values - assert "Product1" == result[0].p_name - assert "Flat" == result[0].type_properties_type - assert "Building 44" == result[0].location - assert "Resource1" == result[0].name - assert "Succeeded" == result[0].provisioning_state - assert "Microsoft.Web/sites" == result[0].type - assert "value1" == result[0].tags["tag1"] - assert "value3" == result[0].tags["tag2"] + assert "1" == result[0].id + assert "OK" == result[0].provisioning_state_values + assert "Product1" == result[0].p_name + assert "Flat" == result[0].type_properties_type + assert "Building 44" == result[0].location + assert "Resource1" == result[0].name + assert "Succeeded" == result[0].provisioning_state + assert "Microsoft.Web/sites" == result[0].type + assert "value1" == result[0].tags["tag1"] + assert "value3" == result[0].tags["tag2"] # Resource 2 - assert "2" == result[1].id - assert "Resource2" == result[1].name - assert "Building 44" == result[1].location + assert "2" == result[1].id + assert "Resource2" == result[1].name + assert "Building 44" == result[1].location # Resource 3 - assert "3" == result[2].id - assert "Resource3" == result[2].name + assert "3" == result[2].id + assert "Resource3" == result[2].name resourceArray = [ - { - 'location': "West US", - 'tags': {"tag1":"value1", "tag2":"value3"}}, - { - 'location': "Building 44"}] + {"location": "West US", "tags": {"tag1": "value1", "tag2": "value3"}}, + {"location": "Building 44"}, + ] await client.put_array(resourceArray) @pytest.mark.asyncio async def test_flattening_dictionary(self, client): - #Dictionary + # Dictionary resultDictionary = await client.get_dictionary() - assert 3 == len(resultDictionary) + assert 3 == len(resultDictionary) # Resource 1 - assert "1" == resultDictionary["Product1"].id - assert "OK" == resultDictionary["Product1"].provisioning_state_values - assert "Product1" == resultDictionary["Product1"].p_name - assert "Flat" == resultDictionary["Product1"].type_properties_type - assert "Building 44" == resultDictionary["Product1"].location - assert "Resource1" == resultDictionary["Product1"].name - assert "Succeeded" == resultDictionary["Product1"].provisioning_state - assert "Microsoft.Web/sites" == resultDictionary["Product1"].type - assert "value1" == resultDictionary["Product1"].tags["tag1"] - assert "value3" == resultDictionary["Product1"].tags["tag2"] + assert "1" == resultDictionary["Product1"].id + assert "OK" == resultDictionary["Product1"].provisioning_state_values + assert "Product1" == resultDictionary["Product1"].p_name + assert "Flat" == resultDictionary["Product1"].type_properties_type + assert "Building 44" == resultDictionary["Product1"].location + assert "Resource1" == resultDictionary["Product1"].name + assert "Succeeded" == resultDictionary["Product1"].provisioning_state + assert "Microsoft.Web/sites" == resultDictionary["Product1"].type + assert "value1" == resultDictionary["Product1"].tags["tag1"] + assert "value3" == resultDictionary["Product1"].tags["tag2"] # Resource 2 - assert "2" == resultDictionary["Product2"].id - assert "Resource2" == resultDictionary["Product2"].name - assert "Building 44" == resultDictionary["Product2"].location + assert "2" == resultDictionary["Product2"].id + assert "Resource2" == resultDictionary["Product2"].name + assert "Building 44" == resultDictionary["Product2"].location # Resource 3 - assert "3" == resultDictionary["Product3"].id - assert "Resource3" == resultDictionary["Product3"].name + assert "3" == resultDictionary["Product3"].id + assert "Resource3" == resultDictionary["Product3"].name resourceDictionary = { - "Resource1": { - 'location': "West US", - 'tags': {"tag1":"value1", "tag2":"value3"}, - 'p_name': "Product1", - 'type_properties_type': "Flat"}, - "Resource2": { - 'location': "Building 44", - 'p_name': "Product2", - 'type_properties_type': "Flat"}} + "Resource1": { + "location": "West US", + "tags": {"tag1": "value1", "tag2": "value3"}, + "p_name": "Product1", + "type_properties_type": "Flat", + }, + "Resource2": {"location": "Building 44", "p_name": "Product2", "type_properties_type": "Flat"}, + } await client.put_dictionary(resourceDictionary) @pytest.mark.asyncio async def test_flattening_complex_object(self, client): - #ResourceCollection + # ResourceCollection resultResource = await client.get_resource_collection() - #dictionaryofresources - assert 3 == len(resultResource.dictionaryofresources) + # dictionaryofresources + assert 3 == len(resultResource.dictionaryofresources) # Resource 1 - assert "1" == resultResource.dictionaryofresources["Product1"].id - assert "OK" == resultResource.dictionaryofresources["Product1"].provisioning_state_values - assert "Product1" == resultResource.dictionaryofresources["Product1"].p_name - assert "Flat" == resultResource.dictionaryofresources["Product1"].type_properties_type - assert "Building 44" == resultResource.dictionaryofresources["Product1"].location - assert "Resource1" == resultResource.dictionaryofresources["Product1"].name - assert "Succeeded" == resultResource.dictionaryofresources["Product1"].provisioning_state - assert "Microsoft.Web/sites" == resultResource.dictionaryofresources["Product1"].type - assert "value1" == resultResource.dictionaryofresources["Product1"].tags["tag1"] - assert "value3" == resultResource.dictionaryofresources["Product1"].tags["tag2"] + assert "1" == resultResource.dictionaryofresources["Product1"].id + assert "OK" == resultResource.dictionaryofresources["Product1"].provisioning_state_values + assert "Product1" == resultResource.dictionaryofresources["Product1"].p_name + assert "Flat" == resultResource.dictionaryofresources["Product1"].type_properties_type + assert "Building 44" == resultResource.dictionaryofresources["Product1"].location + assert "Resource1" == resultResource.dictionaryofresources["Product1"].name + assert "Succeeded" == resultResource.dictionaryofresources["Product1"].provisioning_state + assert "Microsoft.Web/sites" == resultResource.dictionaryofresources["Product1"].type + assert "value1" == resultResource.dictionaryofresources["Product1"].tags["tag1"] + assert "value3" == resultResource.dictionaryofresources["Product1"].tags["tag2"] # Resource 2 - assert "2" == resultResource.dictionaryofresources["Product2"].id - assert "Resource2" == resultResource.dictionaryofresources["Product2"].name - assert "Building 44" == resultResource.dictionaryofresources["Product2"].location + assert "2" == resultResource.dictionaryofresources["Product2"].id + assert "Resource2" == resultResource.dictionaryofresources["Product2"].name + assert "Building 44" == resultResource.dictionaryofresources["Product2"].location # Resource 3 - assert "3" == resultResource.dictionaryofresources["Product3"].id - assert "Resource3" == resultResource.dictionaryofresources["Product3"].name + assert "3" == resultResource.dictionaryofresources["Product3"].id + assert "Resource3" == resultResource.dictionaryofresources["Product3"].name - #arrayofresources - assert 3 == len(resultResource.arrayofresources) + # arrayofresources + assert 3 == len(resultResource.arrayofresources) # Resource 1 - assert "4" == resultResource.arrayofresources[0].id - assert "OK" == resultResource.arrayofresources[0].provisioning_state_values - assert "Product4" == resultResource.arrayofresources[0].p_name - assert "Flat" == resultResource.arrayofresources[0].type_properties_type - assert "Building 44" == resultResource.arrayofresources[0].location - assert "Resource4" == resultResource.arrayofresources[0].name - assert "Succeeded" == resultResource.arrayofresources[0].provisioning_state - assert "Microsoft.Web/sites" == resultResource.arrayofresources[0].type - assert "value1" == resultResource.arrayofresources[0].tags["tag1"] - assert "value3" == resultResource.arrayofresources[0].tags["tag2"] + assert "4" == resultResource.arrayofresources[0].id + assert "OK" == resultResource.arrayofresources[0].provisioning_state_values + assert "Product4" == resultResource.arrayofresources[0].p_name + assert "Flat" == resultResource.arrayofresources[0].type_properties_type + assert "Building 44" == resultResource.arrayofresources[0].location + assert "Resource4" == resultResource.arrayofresources[0].name + assert "Succeeded" == resultResource.arrayofresources[0].provisioning_state + assert "Microsoft.Web/sites" == resultResource.arrayofresources[0].type + assert "value1" == resultResource.arrayofresources[0].tags["tag1"] + assert "value3" == resultResource.arrayofresources[0].tags["tag2"] # Resource 2 - assert "5" == resultResource.arrayofresources[1].id - assert "Resource5" == resultResource.arrayofresources[1].name - assert "Building 44" == resultResource.arrayofresources[1].location + assert "5" == resultResource.arrayofresources[1].id + assert "Resource5" == resultResource.arrayofresources[1].name + assert "Building 44" == resultResource.arrayofresources[1].location # Resource 3 - assert "6" == resultResource.arrayofresources[2].id - assert "Resource6" == resultResource.arrayofresources[2].name + assert "6" == resultResource.arrayofresources[2].id + assert "Resource6" == resultResource.arrayofresources[2].name - #productresource - assert "7" == resultResource.productresource.id - assert "Resource7" == resultResource.productresource.name + # productresource + assert "7" == resultResource.productresource.id + assert "Resource7" == resultResource.productresource.name resourceDictionary = { - "Resource1": FlattenedProduct( - location = "West US", - tags = {"tag1":"value1", "tag2":"value3"}, - p_name = "Product1", - type_properties_type = "Flat"), - "Resource2": FlattenedProduct( - location = "Building 44", - p_name = "Product2", - type_properties_type = "Flat")} + "Resource1": FlattenedProduct( + location="West US", + tags={"tag1": "value1", "tag2": "value3"}, + p_name="Product1", + type_properties_type="Flat", + ), + "Resource2": FlattenedProduct(location="Building 44", p_name="Product2", type_properties_type="Flat"), + } resourceComplexObject = ResourceCollection( - dictionaryofresources = resourceDictionary, - arrayofresources = [ - FlattenedProduct( - location = "West US", - tags = {"tag1":"value1", "tag2":"value3"}, - p_name = "Product1", - type_properties_type = "Flat"), - FlattenedProduct( - location = "East US", - p_name = "Product2", - type_properties_type = "Flat")], - productresource = FlattenedProduct( - location = "India", - p_name = "Azure", - type_properties_type = "Flat")) + dictionaryofresources=resourceDictionary, + arrayofresources=[ + FlattenedProduct( + location="West US", + tags={"tag1": "value1", "tag2": "value3"}, + p_name="Product1", + type_properties_type="Flat", + ), + FlattenedProduct(location="East US", p_name="Product2", type_properties_type="Flat"), + ], + productresource=FlattenedProduct(location="India", p_name="Azure", type_properties_type="Flat"), + ) await client.put_resource_collection(resourceComplexObject) @@ -209,63 +201,64 @@ async def test_flattening_complex_object(self, client): async def test_model_flattening_simple(self, client): simple_product = SimpleProduct( - product_id = "123", - description = "product description", - max_product_display_name = "max name", + product_id="123", + description="product description", + max_product_display_name="max name", capacity="Large", - odata_value = "http://foo", - generic_value = "https://generic" + odata_value="http://foo", + generic_value="https://generic", ) - simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. + simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. result = await client.put_simple_product(simple_product) - result.additional_properties = {} # Not the purpose of this test. This enables the ==. - assert result == simple_product + result.additional_properties = {} # Not the purpose of this test. This enables the ==. + assert result == simple_product @pytest.mark.asyncio async def test_model_flattening_with_parameter_flattening(self, client): simple_product = SimpleProduct( - product_id = "123", - description = "product description", - max_product_display_name = "max name", + product_id="123", + description="product description", + max_product_display_name="max name", capacity="Large", - odata_value = "http://foo" + odata_value="http://foo", ) - simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. + simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. result = await client.post_flattened_simple_product( - "123", # product_id - "product description", # description - "max name", # max_product_display_name + "123", # product_id + "product description", # description + "max name", # max_product_display_name "Large", # capacity - None, # generic_value - "http://foo", # odata_value + None, # generic_value + "http://foo", # odata_value ) - result.additional_properties = {} # Not the purpose of this test. This enables the ==. - assert result == simple_product + result.additional_properties = {} # Not the purpose of this test. This enables the ==. + assert result == simple_product @pytest.mark.asyncio async def test_model_flattening_with_grouping(self, client): from modelflattening.models import FlattenParameterGroup simple_product = SimpleProduct( - product_id = "123", - description = "product description", - max_product_display_name = "max name", + product_id="123", + description="product description", + max_product_display_name="max name", capacity="Large", - odata_value = "http://foo" + odata_value="http://foo", ) - simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. + simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. group = FlattenParameterGroup( - product_id = "123", - description = "product description", + product_id="123", + description="product description", max_product_display_name="max name", capacity="Large", odata_value="http://foo", - name="groupproduct") + name="groupproduct", + ) result = await client.put_simple_product_with_grouping(group) - result.additional_properties = {} # Not the purpose of this test. This enables the ==. - assert result == simple_product + result.additional_properties = {} # Not the purpose of this test. This enables the ==. + assert result == simple_product diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_multiple_inheritance.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_multiple_inheritance.py index 8d63b9a78f6..8b1f667f3f0 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_multiple_inheritance.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_multiple_inheritance.py @@ -30,12 +30,14 @@ from multipleinheritance.models import * import pytest + @pytest.fixture @async_generator async def client(): async with MultipleInheritanceServiceClient(base_url="http://localhost:3000") as client: await yield_(client) + class TestMultipleInheritance(object): @pytest.mark.asyncio @@ -76,9 +78,14 @@ async def test_put_cat(self, client): @pytest.mark.asyncio async def test_get_kitten(self, client): - assert Kitten(name="Gatito", likes_milk=True, meows=True, hisses=True, eats_mice_yet=False) == await client.get_kitten() + assert ( + Kitten(name="Gatito", likes_milk=True, meows=True, hisses=True, eats_mice_yet=False) + == await client.get_kitten() + ) @pytest.mark.asyncio async def test_put_kitten(self, client): - result = await client.put_kitten(Kitten(name="Kitty", likes_milk=False, meows=True, hisses=False, eats_mice_yet=True)) + result = await client.put_kitten( + Kitten(name="Kitty", likes_milk=False, meows=True, hisses=False, eats_mice_yet=True) + ) assert result == "Kitten was correct!" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_non_string_enums.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_non_string_enums.py index 839f88463f2..6e709cedbd8 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_non_string_enums.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_non_string_enums.py @@ -30,6 +30,7 @@ import pytest import json + @pytest.fixture @async_generator async def client(): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_number.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_number.py index 869ba209ad9..c2a45ecd93d 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_number.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_number.py @@ -42,63 +42,65 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestNumberTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestNumber(object): @pytest.mark.asyncio async def test_big_float(self, client): - await client.number.put_big_float(3.402823e+20) - assert (await client.number.get_big_float()) == 3.402823e+20 + await client.number.put_big_float(3.402823e20) + assert (await client.number.get_big_float()) == 3.402823e20 @pytest.mark.asyncio async def test_small_float(self, client): await client.number.put_small_float(3.402823e-20) - assert (await client.number.get_small_float()) == 3.402823e-20 + assert (await client.number.get_small_float()) == 3.402823e-20 @pytest.mark.asyncio async def test_big_double(self, client): - await client.number.put_big_double(2.5976931e+101) - assert (await client.number.get_big_double()) == 2.5976931e+101 + await client.number.put_big_double(2.5976931e101) + assert (await client.number.get_big_double()) == 2.5976931e101 @pytest.mark.asyncio async def test_small_double(self, client): await client.number.put_small_double(2.5976931e-101) - assert (await client.number.get_small_double()) == 2.5976931e-101 + assert (await client.number.get_small_double()) == 2.5976931e-101 @pytest.mark.asyncio async def test_big_double_negative_decimal(self, client): await client.number.put_big_double_negative_decimal() - assert (await client.number.get_big_double_negative_decimal()) == -99999999.99 + assert (await client.number.get_big_double_negative_decimal()) == -99999999.99 @pytest.mark.asyncio async def test_big_double_positive_decimal(self, client): await client.number.put_big_double_positive_decimal() - assert (await client.number.get_big_double_positive_decimal()) == 99999999.99 + assert (await client.number.get_big_double_positive_decimal()) == 99999999.99 @pytest.mark.asyncio async def test_big_decimal(self, client): - await client.number.put_big_decimal(Decimal(2.5976931e+101)) - assert (await client.number.get_big_decimal()) == 2.5976931e+101 + await client.number.put_big_decimal(Decimal(2.5976931e101)) + assert (await client.number.get_big_decimal()) == 2.5976931e101 @pytest.mark.asyncio async def test_small_decimal(self, client): await client.number.put_small_decimal(Decimal(2.5976931e-101)) - assert (await client.number.get_small_decimal()) == 2.5976931e-101 + assert (await client.number.get_small_decimal()) == 2.5976931e-101 @pytest.mark.asyncio async def test_get_big_decimal_negative_decimal(self, client): await client.number.put_big_decimal_positive_decimal() - assert (await client.number.get_big_decimal_negative_decimal()) == -99999999.99 + assert (await client.number.get_big_decimal_negative_decimal()) == -99999999.99 @pytest.mark.asyncio async def test_get_big_decimal_positive_decimal(self, client): await client.number.put_big_decimal_negative_decimal() - assert (await client.number.get_big_decimal_positive_decimal()) == 99999999.99 + assert (await client.number.get_big_decimal_positive_decimal()) == 99999999.99 @pytest.mark.asyncio async def test_get_null(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_object_type.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_object_type.py index cec98006511..ae5b4b800d0 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_object_type.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_object_type.py @@ -29,12 +29,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with ObjectTypeClient(base_url="http://localhost:3000") as client: await yield_(client) + class TestObjectType(object): @pytest.mark.asyncio @@ -51,4 +53,4 @@ async def test_put_object_success(self, client): async def test_put_object_fail(self, client): with pytest.raises(HttpResponseError) as ex: response = await client.put({"should": "fail"}) - assert ex.value.model == {"message": "The object you passed was incorrect"} \ No newline at end of file + assert ex.value.model == {"message": "The object you passed was incorrect"} diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_parameterized_endpoint.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_parameterized_endpoint.py index 6f6c38d479a..a0b091fcdcd 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_parameterized_endpoint.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_parameterized_endpoint.py @@ -26,11 +26,13 @@ import pytest from parameterizedendpoint.aio import ParmaterizedEndpointClient + @pytest.fixture async def client(): async with ParmaterizedEndpointClient(endpoint="http://localhost:3000") as client: yield client + @pytest.mark.asyncio async def test_get(client): await client.get() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_required_optional.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_required_optional.py index 075a84a1d1c..b4100f910f7 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_required_optional.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_required_optional.py @@ -42,28 +42,29 @@ import pytest + @pytest.fixture @async_generator async def client_required(): async with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - base_url="http://localhost:3000") as client: + "required_path", "required_query", base_url="http://localhost:3000" + ) as client: client._config.required_global_path = "required_path" client._config.required_global_query = "required_query" await yield_(client) + @pytest.fixture @async_generator async def client(): async with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - base_url="http://localhost:3000") as client: + "required_path", "required_query", base_url="http://localhost:3000" + ) as client: client._config.required_global_path = None client._config.required_global_query = None await yield_(client) + class TestRequiredOptional(object): # These clients have a required global path and query @@ -148,12 +149,11 @@ async def test_explict_put_optional_binary_body(self, client): @pytest.mark.asyncio async def test_explict_put_required_binary_body(self, client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: await client.explicit.put_required_binary_body(stream_data) - @pytest.mark.asyncio async def test_implicit_put_optional_binary_body(self, client): - await client.implicit.put_optional_binary_body() \ No newline at end of file + await client.implicit.put_optional_binary_body() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_reserved_words.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_reserved_words.py index 42adcf57d8a..9c70f27c289 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_reserved_words.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_reserved_words.py @@ -26,35 +26,43 @@ import pytest from reservedwords import models, aio + @pytest.fixture async def client(): async with aio.ReservedWordsClient() as client: yield client + @pytest.mark.asyncio async def test_operation_group_import(client): await client.import_operations.operation_one(parameter1="foo") + @pytest.mark.asyncio async def test_operation_with_content_param(client): await client.operation_with_content_param(b"hello, world") + @pytest.mark.asyncio async def test_operation_with_json_param(client): await client.operation_with_json_param({"hello": "world"}) + @pytest.mark.asyncio async def test_operation_with_data_param(client): await client.operation_with_data_param(data="hello", world="world") + @pytest.mark.asyncio async def test_operation_with_files_param(client): await client.operation_with_files_param(file_name="my.txt", files=b"bytes") + @pytest.mark.asyncio async def test_operation_with_url(client): await client.operation_with_url("foo", header_parameters="x-ms-header", query_parameters=["one", "two"]) + @pytest.mark.asyncio async def test_operation_with_enum(client): await client.reserved_enum(models.MyEnum.IMPORT_ENUM) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_security.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_security.py index 659ff48e853..06ac0629e93 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_security.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_security.py @@ -32,28 +32,31 @@ from azure.core.pipeline.policies import AzureKeyCredentialPolicy from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy + @pytest.mark.asyncio async def test_security_aad_swagger(credential_async): client = AutorestSecurityAad(credential=credential_async) assert isinstance(client._config.authentication_policy, AsyncBearerTokenCredentialPolicy) await client.head(enforce_https=False) + @pytest.mark.asyncio async def test_security_key_swagger(): # the key value shall keep same with https://github.com/Azure/autorest.testserver/tree/main/src/test-routes/security.ts - client = AutorestSecurityKey(credential=AzureKeyCredential('123456789')) + client = AutorestSecurityKey(credential=AzureKeyCredential("123456789")) assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) await client.head() + @pytest.mark.asyncio async def test_security_aad_swagger_cred_flag(): - client = SecurityAadSwaggerCredentialFlag(credential=AzureKeyCredential('123456789')) + client = SecurityAadSwaggerCredentialFlag(credential=AzureKeyCredential("123456789")) assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) + @pytest.mark.asyncio async def test_security_key_swagger_cred_flag(credential): client = SecurityKeySwaggerCredentialFlag( - credential=credential, - credential_scopes=['https://fake.azure.com/.default'] + credential=credential, credential_scopes=["https://fake.azure.com/.default"] ) assert isinstance(client._config.authentication_policy, AsyncBearerTokenCredentialPolicy) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_send_request.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_send_request.py index 17eb32103f3..b21e98d27de 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_send_request.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_send_request.py @@ -43,18 +43,18 @@ async def test_send_request_with_body_get_model_deserialize(self): client = AutoRestComplexTestService(base_url="http://localhost:3000") - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) async with AutoRestComplexTestService(base_url="http://localhost:3000") as client: response = await client._send_request(request) deserialized = Siamese.deserialize(response) - assert 2 == deserialized.id - assert "Siameeee" == deserialized.name - assert -1 == deserialized.hates[1].id + assert 2 == deserialized.id + assert "Siameeee" == deserialized.name + assert -1 == deserialized.hates[1].id assert "Tomato" == deserialized.hates[1].name @pytest.mark.asyncio @@ -62,11 +62,10 @@ async def test_send_request_with_body_get_direct_json(self): from bodycomplex.aio import AutoRestComplexTestService from bodycomplex.models import Siamese - - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) async with AutoRestComplexTestService(base_url="http://localhost:3000") as client: @@ -74,12 +73,12 @@ async def test_send_request_with_body_get_direct_json(self): chunks = [] async for chunk in response.stream_download(None): chunks.append(chunk) - data = b''.join(chunks).decode('utf-8') + data = b"".join(chunks).decode("utf-8") json_response = json.loads(data) - assert 2 == json_response['id'] - assert "Siameeee" == json_response['name'] - assert - 1 == json_response['hates'][1]['id'] - assert "Tomato" == json_response['hates'][1]['name'] + assert 2 == json_response["id"] + assert "Siameeee" == json_response["name"] + assert -1 == json_response["hates"][1]["id"] + assert "Tomato" == json_response["hates"][1]["name"] @pytest.mark.asyncio async def test_send_request_with_body_put_json_dumps(self): @@ -89,27 +88,14 @@ async def test_send_request_with_body_put_json_dumps(self): "id": 2, "name": "Siameeee", "color": "green", - "hates": - [ - { - "id": 1, - "name": "Potato", - "food": "tomato" - }, - { - "id": -1, - "name": "Tomato", - "food": "french fries" - } - ], - "breed": "persian" + "hates": [ + {"id": 1, "name": "Potato", "food": "tomato"}, + {"id": -1, "name": "Tomato", "food": "french fries"}, + ], + "breed": "persian", } - request = HttpRequest("PUT", "/complex/inheritance/valid", - headers={ - 'Content-Type': 'application/json' - } - ) + request = HttpRequest("PUT", "/complex/inheritance/valid", headers={"Content-Type": "application/json"}) request.set_json_body(siamese_body) async with AutoRestComplexTestService(base_url="http://localhost:3000") as client: response = await client._send_request(request) @@ -124,26 +110,11 @@ async def test_send_request_with_body_serialize(self): id=2, name="Siameeee", color="green", - hates=[ - Dog( - id=1, - name="Potato", - food="tomato" - ), - Dog( - id=-1, - name="Tomato", - food="french fries" - ) - ], - breed="persian" + hates=[Dog(id=1, name="Potato", food="tomato"), Dog(id=-1, name="Tomato", food="french fries")], + breed="persian", ) - request = HttpRequest("PUT", "/complex/inheritance/valid", - headers={ - 'Content-Type': 'application/json' - } - ) + request = HttpRequest("PUT", "/complex/inheritance/valid", headers={"Content-Type": "application/json"}) request.set_json_body(siamese.serialize()) async with AutoRestComplexTestService(base_url="http://localhost:3000") as client: response = await client._send_request(request) @@ -157,10 +128,10 @@ async def test_send_request_get_stream(self): file_length = 0 with io.BytesIO() as file_handle: - request = HttpRequest("GET", "/files/stream/nonempty", - headers={ - 'Accept': 'image/png, application/json' - }, + request = HttpRequest( + "GET", + "/files/stream/nonempty", + headers={"Accept": "image/png, application/json"}, ) response = await client._send_request(request, stream=True) @@ -174,16 +145,28 @@ async def test_send_request_get_stream(self): async for data in stream: assert 0 < len(data) <= stream.block_size file_length += len(data) - print("Downloading... {}%".format(int(file_length*100/total))) + print("Downloading... {}%".format(int(file_length * 100 / total))) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) + join( + cwd, + pardir, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) - with open(sample_file, 'rb') as data: + with open(sample_file, "rb") as data: sample_data = hash(data.read()) assert sample_data == hash(file_handle.getvalue()) await client.close() @@ -197,12 +180,12 @@ async def test_send_request_put_stream(self): ) test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: - request = HttpRequest("PUT", '/formdata/stream/uploadfile', - headers={ - 'Content-Type': 'application/octet-stream' - }, + request = HttpRequest( + "PUT", + "/formdata/stream/uploadfile", + headers={"Content-Type": "application/octet-stream"}, data=stream_data, ) response = await client._send_request(request, stream=True) @@ -214,16 +197,16 @@ async def test_send_request_full_url(self): from bodycomplex.aio import AutoRestComplexTestService from bodycomplex.models import Siamese - request = HttpRequest("GET", "http://localhost:3000/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "http://localhost:3000/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) async with AutoRestComplexTestService(base_url="http://fakeUrl") as client: response = await client._send_request(request) deserialized = Siamese.deserialize(response) - assert 2 == deserialized.id - assert "Siameeee" == deserialized.name - assert -1 == deserialized.hates[1].id - assert "Tomato" == deserialized.hates[1].name + assert 2 == deserialized.id + assert "Siameeee" == deserialized.name + assert -1 == deserialized.hates[1].id + assert "Tomato" == deserialized.hates[1].name diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_string_tests.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_string_tests.py index 95651fa38a5..ffca95aea44 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_string_tests.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_string_tests.py @@ -43,12 +43,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATService(base_url="http://localhost:3000") as client: await yield_(client) + class TestString(object): @pytest.mark.asyncio @@ -58,7 +60,7 @@ async def test_null(self, client): @pytest.mark.asyncio async def test_empty(self, client): - assert "" == (await client.string.get_empty()) + assert "" == (await client.string.get_empty()) # changing this behavior because of this pr being merged: https://github.com/Azure/autorest.testserver/pull/145/files await client.string.put_empty() @@ -79,7 +81,8 @@ async def test_mbcs(self, client): "\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" "\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" "\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") except AttributeError: test_str = ( @@ -96,7 +99,8 @@ async def test_mbcs(self, client): b"\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" b"\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" b"\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") assert test_str == (await client.string.get_mbcs()) await client.string.put_mbcs() @@ -104,7 +108,7 @@ async def test_mbcs(self, client): @pytest.mark.asyncio async def test_whitespace(self, client): test_str = " Now is the time for all good men to come to the aid of their country " - assert test_str == (await client.string.get_whitespace()) + assert test_str == (await client.string.get_whitespace()) await client.string.put_whitespace() @pytest.mark.asyncio @@ -113,20 +117,20 @@ async def test_get_not_provided(self, client): @pytest.mark.asyncio async def test_enum_not_expandable(self, client): - assert Colors.RED_COLOR == (await client.enum.get_not_expandable()) - await client.enum.put_not_expandable('red color') + assert Colors.RED_COLOR == (await client.enum.get_not_expandable()) + await client.enum.put_not_expandable("red color") await client.enum.put_not_expandable(Colors.RED_COLOR) with pytest.raises(HttpResponseError): - await client.enum.put_not_expandable('not a colour') + await client.enum.put_not_expandable("not a colour") @pytest.mark.asyncio async def test_get_base64_encdoded(self, client): - assert (await client.string.get_base64_encoded()) == 'a string that gets encoded with base64'.encode() + assert (await client.string.get_base64_encoded()) == "a string that gets encoded with base64".encode() @pytest.mark.asyncio async def test_base64_url_encoded(self, client): - assert (await client.string.get_base64_url_encoded()) == 'a string that gets encoded with base64url'.encode() - await client.string.put_base64_url_encoded('a string that gets encoded with base64url'.encode()) + assert (await client.string.get_base64_url_encoded()) == "a string that gets encoded with base64url".encode() + await client.string.put_base64_url_encoded("a string that gets encoded with base64url".encode()) @pytest.mark.asyncio async def test_get_null_base64_url_encoded(self, client): @@ -137,12 +141,12 @@ async def test_enum_referenced(self, client): await client.enum.put_referenced(Colors.RED_COLOR) await client.enum.put_referenced("red color") - assert (await client.enum.get_referenced()) == Colors.RED_COLOR + assert (await client.enum.get_referenced()) == Colors.RED_COLOR @pytest.mark.asyncio async def test_enum_referenced_constant(self, client): await client.enum.put_referenced_constant() - assert (await client.enum.get_referenced_constant()).color_constant == Colors.GREEN_COLOR.value + assert (await client.enum.get_referenced_constant()).color_constant == Colors.GREEN_COLOR.value def test_patch_file(self): from bodystring.models import PatchAddedModel diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_time.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_time.py index ccb97e8f435..8e87d9d0898 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_time.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_time.py @@ -31,12 +31,14 @@ from bodytime.aio import AutoRestTimeTestService import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestTimeTestService(base_url="http://localhost:3000") as client: await yield_(client) + class TestTime(object): @pytest.mark.asyncio diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_tracing.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_tracing.py index 1fed5e1a157..f1df7a5486d 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_tracing.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_tracing.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -42,4 +41,4 @@ def has_tracing_decorator(function): def test_url(): client = AutoRestUrlTestService("", base_url="dummy url") - assert has_tracing_decorator(client.paths.get_boolean_false) \ No newline at end of file + assert has_tracing_decorator(client.paths.get_boolean_false) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_url.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_url.py index 2429fa2d8ff..2804bc95359 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_url.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_url.py @@ -46,19 +46,22 @@ @pytest.fixture @async_generator async def client(): - async with AutoRestUrlTestService('', base_url="http://localhost:3000") as client: + async with AutoRestUrlTestService("", base_url="http://localhost:3000") as client: await yield_(client) + @pytest.fixture @async_generator async def multi_client(): async with AutoRestUrlMutliCollectionFormatTestService("http://localhost:3000") as client: await yield_(client) + @pytest.fixture def test_array_query(): return ["ArrayQuery1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + class TestUrl(object): @pytest.mark.asyncio @@ -70,7 +73,7 @@ async def test_byte_empty_and_null(self, client): @pytest.mark.asyncio async def test_byte_multi_byte(self, client): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") await client.paths.byte_multi_byte(u_bytes) @pytest.mark.asyncio @@ -160,7 +163,7 @@ async def test_base64_url(self, client): @pytest.mark.asyncio async def test_queries_byte(self, client): await client.queries.byte_empty() - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") await client.queries.byte_multi_byte(u_bytes) await client.queries.byte_null() @@ -243,7 +246,7 @@ async def test_array_string_multi(self, multi_client, test_array_query): @pytest.mark.asyncio async def test_array_string_no_collection_format(self, client): - await client.queries.array_string_no_collection_format_empty(['hello', 'nihao', 'bonjour']) + await client.queries.array_string_no_collection_format_empty(["hello", "nihao", "bonjour"]) @pytest.mark.asyncio async def test_get_all_with_values(self, client): diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_urlencoded.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_urlencoded.py index 6c559b241bf..07a272836b0 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_urlencoded.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_urlencoded.py @@ -28,11 +28,13 @@ from bodyformurlencodeddata.aio import BodyFormsDataURLEncoded from bodyformurlencodeddata.models import PetFood, PetType + @pytest.fixture async def client(): async with BodyFormsDataURLEncoded() as client: yield client + @pytest.mark.asyncio async def test_update_pet_with_form(client): await client.formdataurlencoded.update_pet_with_form( @@ -43,6 +45,7 @@ async def test_update_pet_with_form(client): name="Fido", ) + @pytest.mark.asyncio async def test_partial_constant_body(client): await client.formdataurlencoded.partial_constant_body(access_token="foo", service="bar") diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_validation.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_validation.py index cafe016b258..f16eac9051b 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_validation.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_validation.py @@ -38,34 +38,32 @@ from msrest.exceptions import ValidationError from validation.aio import AutoRestValidationTest -from validation.models import ( - Product, - ConstantProduct, - ChildProduct) +from validation.models import Product, ConstantProduct, ChildProduct import pytest + @pytest.fixture @async_generator async def client(): - async with AutoRestValidationTest( - "abc123", - base_url="http://localhost:3000") as client: + async with AutoRestValidationTest("abc123", base_url="http://localhost:3000") as client: client.api_version = "12-34-5678" await yield_(client) + @pytest.fixture def constant_body(): """This is NOT considering the constant body, this should work with the commented line. See https://github.com/Azure/autorest.modelerfour/issues/83 """ - #return Product(child=ChildProduct()) + # return Product(child=ChildProduct()) return Product( child=ChildProduct(), const_child=ConstantProduct(), ) + class TestValidation(object): @pytest.mark.asyncio @@ -82,48 +80,48 @@ async def test_min_length_validation(self, client): try: await client.validation_of_method_parameters("1", 100) except ValidationError as err: - assert err.rule == "min_length" - assert err.target == "resource_group_name" + assert err.rule == "min_length" + assert err.target == "resource_group_name" @pytest.mark.asyncio async def test_max_length_validation(self, client): try: await client.validation_of_method_parameters("1234567890A", 100) except ValidationError as err: - assert err.rule == "max_length" - assert err.target == "resource_group_name" + assert err.rule == "max_length" + assert err.target == "resource_group_name" @pytest.mark.asyncio async def test_pattern_validation(self, client): try: await client.validation_of_method_parameters("!@#$", 100) except ValidationError as err: - assert err.rule == "pattern" - assert err.target == "resource_group_name" + assert err.rule == "pattern" + assert err.target == "resource_group_name" @pytest.mark.asyncio async def test_multiple_validation(self, client): try: await client.validation_of_method_parameters("123", 105) except ValidationError as err: - assert err.rule == "multiple" - assert err.target == "id" + assert err.rule == "multiple" + assert err.target == "id" @pytest.mark.asyncio async def test_minimum_validation(self, client): try: await client.validation_of_method_parameters("123", 0) except ValidationError as err: - assert err.rule == "minimum" - assert err.target == "id" + assert err.rule == "minimum" + assert err.target == "id" @pytest.mark.asyncio async def test_maximum_validation(self, client): try: await client.validation_of_method_parameters("123", 2000) except ValidationError as err: - assert err.rule == "maximum" - assert err.target == "id" + assert err.rule == "maximum" + assert err.target == "id" @pytest.mark.asyncio async def test_minimum_ex_validation(self, client, constant_body): @@ -131,8 +129,8 @@ async def test_minimum_ex_validation(self, client, constant_body): constant_body.capacity = 0 await client.validation_of_body("123", 150, constant_body) except ValidationError as err: - assert err.rule == "minimum_ex" - assert "capacity" in err.target + assert err.rule == "minimum_ex" + assert "capacity" in err.target @pytest.mark.asyncio async def test_maximum_ex_validation(self, client, constant_body): @@ -140,27 +138,25 @@ async def test_maximum_ex_validation(self, client, constant_body): constant_body.capacity = 100 await client.validation_of_body("123", 150, constant_body) except ValidationError as err: - assert err.rule == "maximum_ex" - assert "capacity" in err.target + assert err.rule == "maximum_ex" + assert "capacity" in err.target @pytest.mark.asyncio async def test_max_items_validation(self, client, constant_body): try: - constant_body.display_names = ["item1","item2","item3","item4","item5","item6","item7"] + constant_body.display_names = ["item1", "item2", "item3", "item4", "item5", "item6", "item7"] await client.validation_of_body("123", 150, constant_body) except ValidationError as err: - assert err.rule == "max_items" - assert "display_names" in err.target + assert err.rule == "max_items" + assert "display_names" in err.target @pytest.mark.xfail(reason="https://github.com/Azure/autorest.modelerfour/issues/90") @pytest.mark.asyncio async def test_api_version_validation(self): - with AutoRestValidationTest( - "abc123", - base_url="http://localhost:3000") as client: + with AutoRestValidationTest("abc123", base_url="http://localhost:3000") as client: client.api_version = "abc" try: await client.validation_of_method_parameters("123", 150) except ValidationError as err: - assert err.rule == "pattern" - assert err.target == "self.api_version" + assert err.rule == "pattern" + assert err.target == "self.api_version" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xml.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xml.py index 4f57a2c5338..bb8b38c2873 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xml.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xml.py @@ -41,15 +41,18 @@ _LOGGER = logging.getLogger(__name__) + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATXMLService(base_url="http://localhost:3000") as client: await yield_(client) + async def _assert_with_log(func, *args, **kwargs): def raise_for_status(response, deserialized, headers): response.http_response.internal_response.raise_for_status() + try: http_response = await func(*args, cls=raise_for_status, **kwargs) except Exception as err: @@ -87,7 +90,7 @@ async def test_simple(self, client): assert slide2.title == "Overview" assert len(slide2.items) == 3 assert slide2.items[0] == "Why WonderWidgets are great" - assert slide2.items[1] == '' + assert slide2.items[1] == "" assert slide2.items[2] == "Who buys WonderWidgets" await _assert_with_log(client.xml.put_simple, slideshow) @@ -95,7 +98,7 @@ async def test_simple(self, client): @pytest.mark.asyncio async def test_empty_child_element(self, client): banana = await client.xml.get_empty_child_element() - assert banana.flavor == '' # That's the point of this test, it was an empty node. + assert banana.flavor == "" # That's the point of this test, it was an empty node. await _assert_with_log(client.xml.put_empty_child_element, banana) @pytest.mark.asyncio @@ -132,8 +135,8 @@ async def test_get_empty(self, client): @pytest.mark.asyncio async def test_wrapped_lists(self, client): bananas = await client.xml.get_wrapped_lists() - assert bananas.good_apples == ['Fuji', 'Gala'] - assert bananas.bad_apples == ['Red Delicious'] + assert bananas.good_apples == ["Fuji", "Gala"] + assert bananas.bad_apples == ["Red Delicious"] await _assert_with_log(client.xml.put_wrapped_lists, bananas) @pytest.mark.asyncio @@ -164,9 +167,9 @@ async def test_list_blobs(self, client): assert blob.properties.content_length == 100 assert blob.properties.content_type == "text/html" # Check that an empty field in the XML is empty string - assert blob.properties.content_encoding == '' + assert blob.properties.content_encoding == "" assert blob.properties.content_language == "en-US" - assert blob.properties.content_md5 == '' + assert blob.properties.content_md5 == "" assert blob.properties.cache_control == "no-cache" assert blob.properties.blob_type == BlobType.block_blob # Check that a field NOT in the XML is None @@ -187,7 +190,7 @@ async def test_service_properties(self, client): async def test_acls(self, client): acls = await client.xml.get_acls() assert len(acls) == 1 - assert acls[0].id == 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' + assert acls[0].id == "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=" await _assert_with_log(client.xml.put_acls, acls) @pytest.mark.asyncio @@ -210,8 +213,8 @@ async def test_put_bytes(self, client): async def test_get_url(self, client): url_object = await client.xml.get_uri() assert isinstance(url_object, ModelWithUrlProperty) - assert url_object.url == 'https://myaccount.blob.core.windows.net/' + assert url_object.url == "https://myaccount.blob.core.windows.net/" @pytest.mark.asyncio async def test_put_url(self, client): - await client.xml.put_uri('https://myaccount.blob.core.windows.net/') \ No newline at end of file + await client.xml.put_uri("https://myaccount.blob.core.windows.net/") diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xms_error.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xms_error.py index d513be75f70..dbbcac9c163 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xms_error.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/asynctests/test_xms_error.py @@ -30,7 +30,15 @@ from azure.core.exceptions import HttpResponseError, ResourceNotFoundError from xmserrorresponse.aio import XMSErrorResponseExtensions -from xmserrorresponse.models import NotFoundErrorBase, AnimalNotFound, LinkNotFound, PetActionError, PetSadError, PetHungryOrThirstyError +from xmserrorresponse.models import ( + NotFoundErrorBase, + AnimalNotFound, + LinkNotFound, + PetActionError, + PetSadError, + PetHungryOrThirstyError, +) + @pytest.fixture @async_generator @@ -47,8 +55,7 @@ async def test_get_by_pet_id_success(self, client): pet = await client.pet.get_pet_by_id("tommy") assert pet.name == "Tommy Tomson" - await client.pet.get_pet_by_id('django') # no fail, 202 - + await client.pet.get_pet_by_id("django") # no fail, 202 @pytest.mark.asyncio async def test_get_by_pet_id_discriminator(self, client): @@ -108,18 +115,20 @@ async def test_error_deserialization_with_param_name_models(self, client): @pytest.mark.asyncio async def test_failsafe_deserialize(self, client): from xmserrorresponse.operations._pet_operations import build_do_something_request + request = build_do_something_request(what_action="jump") request.url = client._client.format_url(request.url) pipeline_response = await client._client._pipeline.run(request) + class MyPetSadError(PetSadError): def read(self): return b"ignore me" - pipeline_response.context['deserialized_data'] = { + pipeline_response.context["deserialized_data"] = { "reason": "Not OK", "errorMessage": "i should be the message", "errorType": "my own error type", - "actionResponse": "hello" + "actionResponse": "hello", } # add pipeline context with deserialized data and pass to failsafe_deserialize diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/conftest.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/conftest.py index b9d2c5c583d..64139e91e42 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/conftest.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/conftest.py @@ -39,21 +39,26 @@ cwd = dirname(realpath(__file__)) -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def start_server_process(): - cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format(cwd) - if os.name == 'nt': #On windows, subprocess creation works without being in the shell + cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format( + cwd + ) + if os.name == "nt": # On windows, subprocess creation works without being in the shell return subprocess.Popen(cmd) - return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) #On linux, have to set shell=True + return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # On linux, have to set shell=True + -#Ideally this would be in a common helper library shared between the tests +# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session") def testserver(): """Start the Autorest testserver.""" @@ -61,6 +66,7 @@ def testserver(): yield terminate_server_process(server) + class CookiePolicy(SansIOHTTPPolicy): def __init__(self, *args, **kwargs): self._current_cookie = None @@ -77,13 +83,16 @@ def on_response(self, request, response, **kwargs): if "Set-Cookie" in http_response.headers: self._current_cookie = http_response.headers["Set-Cookie"] + @pytest.fixture() def cookie_policy(): return CookiePolicy() + # the token value shall keep same with https://github.com/Azure/autorest.testserver/tree/main/src/test-routes/security.ts def generate_token(*scopes) -> AccessToken: - return AccessToken(token=''.join(scopes), expires_on=1800) + return AccessToken(token="".join(scopes), expires_on=1800) + @pytest.fixture() def credential(): @@ -91,12 +100,15 @@ class FakeCredential: @staticmethod def get_token(*scopes) -> AccessToken: return generate_token(*scopes) + return FakeCredential() + @pytest.fixture() def credential_async(): class FakeCredentialAsync: @staticmethod async def get_token(*scopes) -> AccessToken: return generate_token(*scopes) + return FakeCredentialAsync() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_additional_properties.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_additional_properties.py index c368e5642ea..922cde5f8e3 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_additional_properties.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_additional_properties.py @@ -44,113 +44,81 @@ PetAPObject, PetAPString, PetAPInProperties, - PetAPInPropertiesWithAPString + PetAPInPropertiesWithAPString, ) + @pytest.fixture def client(): with AdditionalPropertiesClient(base_url="http://localhost:3000") as client: yield client + class TestAdditionalProperties(object): def test_create_ap_true(self, client): input_ap_true = PetAPTrue( - id = 1, - name = 'Puppy', - additional_properties = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - } + id=1, + name="Puppy", + additional_properties={"birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}}, ) output_ap_true = client.pets.create_ap_true(input_ap_true) - assert output_ap_true.additional_properties['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true.additional_properties["birthdate"] == "2017-12-13T02:29:51Z" def test_create_cat_ap_true(self, client): input_ap_true = CatAPTrue( - id = 1, - name = 'Lisa', - friendly = True, - additional_properties = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - } + id=1, + name="Lisa", + friendly=True, + additional_properties={"birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}}, ) output_ap_true = client.pets.create_cat_ap_true(input_ap_true) - assert output_ap_true.additional_properties['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true.additional_properties["birthdate"] == "2017-12-13T02:29:51Z" def test_create_ap_object(self, client): input_ap_obj = PetAPObject( - id = 2, - name = 'Hira', - additional_properties = { - 'siblings': [{ - 'id': 1, - 'name': 'Puppy', - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - }], - 'picture': '//////4=' - } + id=2, + name="Hira", + additional_properties={ + "siblings": [ + {"id": 1, "name": "Puppy", "birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}} + ], + "picture": "//////4=", + }, ) output_ap_obj = client.pets.create_ap_object(input_ap_obj) - assert output_ap_obj.additional_properties['siblings'][0]['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_obj.additional_properties["siblings"][0]["birthdate"] == "2017-12-13T02:29:51Z" def test_create_ap_string(self, client): input_ap_str = PetAPString( - id = 3, - name = 'Tommy', - additional_properties = { - 'color': 'red', - 'weight': '10 kg', - 'city': 'Bombay' - } + id=3, name="Tommy", additional_properties={"color": "red", "weight": "10 kg", "city": "Bombay"} ) output_ap_str = client.pets.create_ap_string(input_ap_str) - assert output_ap_str.additional_properties['color'] == 'red' + assert output_ap_str.additional_properties["color"] == "red" def test_create_ap_in_properties(self, client): input_ap_int = PetAPInProperties( - id = 4, - name = 'Bunny', - additional_properties = { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } + id=4, name="Bunny", additional_properties={"height": 5.61, "weight": 599, "footsize": 11.5} ) output_ap_int = client.pets.create_ap_in_properties(input_ap_int) - assert output_ap_int.additional_properties['weight'] == 599 + assert output_ap_int.additional_properties["weight"] == 599 def test_create_ap_in_properties_with_ap_string(self, client): input_ap_str_add = PetAPInPropertiesWithAPString( - id = 5, - name = 'Funny', - odata_location = 'westus', - additional_properties = { - 'color': 'red', - 'city': 'Seattle', - 'food': 'tikka masala' - }, - additional_properties1 = { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } + id=5, + name="Funny", + odata_location="westus", + additional_properties={"color": "red", "city": "Seattle", "food": "tikka masala"}, + additional_properties1={"height": 5.61, "weight": 599, "footsize": 11.5}, ) output_ap_str_add = client.pets.create_ap_in_properties_with_ap_string(input_ap_str_add) - assert output_ap_str_add.additional_properties['color'] == 'red' - assert output_ap_str_add.additional_properties1['weight'] == 599 + assert output_ap_str_add.additional_properties["color"] == "red" + assert output_ap_str_add.additional_properties1["weight"] == 599 def test_models(self): from additionalproperties.models import Error from additionalproperties.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -160,4 +128,5 @@ def test_operation_groups(self): from additionalproperties.operations import _pets_operations_py3 from additionalproperties.operations._pets_operations import PetsOperations as PetsOperationsPy2 + assert PetsOperations == PetsOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_anything.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_anything.py index cdcca9fcd25..09807a0f392 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_anything.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_anything.py @@ -27,34 +27,45 @@ import pytest from anything import AnythingClient + @pytest.fixture def client(): with AnythingClient(base_url="http://localhost:3000") as client: yield client + def test_get_string(client): - assert client.get_string() == 'anything' + assert client.get_string() == "anything" + def test_put_string(client): client.put_string(input="anything") + def test_get_object(client): assert client.get_object() == {"message": "An object was successfully returned"} + def test_put_object(client): - client.put_object({'foo': 'bar'}) + client.put_object({"foo": "bar"}) + def test_get_array(client): - assert client.get_array() == ['foo', 'bar'] + assert client.get_array() == ["foo", "bar"] + def test_put_array(client): - client.put_array(['foo', 'bar']) + client.put_array(["foo", "bar"]) + def test_operation_groups(): from anything.operations import AnythingClientOperationsMixin with pytest.raises(ImportError): from anything.operations import _anything_client_operations_py3 - - from anything.operations._anything_client_operations import AnythingClientOperationsMixin as AnythingClientOperationsMixinPy2 - assert AnythingClientOperationsMixin == AnythingClientOperationsMixinPy2 \ No newline at end of file + + from anything.operations._anything_client_operations import ( + AnythingClientOperationsMixin as AnythingClientOperationsMixinPy2, + ) + + assert AnythingClientOperationsMixin == AnythingClientOperationsMixinPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_array.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_array.py index 20df6f60b77..babf37e2bf6 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_array.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_array.py @@ -41,11 +41,13 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATArrayService(base_url="http://localhost:3000") as client: yield client + @pytest.fixture def datetimes(): datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") @@ -53,6 +55,7 @@ def datetimes(): datetime3 = isodate.parse_datetime("1492-10-12T10:15:01Z") return [datetime1, datetime2, datetime3] + @pytest.fixture def products(): prod1 = Product(integer=1, string="2") @@ -60,58 +63,70 @@ def products(): prod3 = Product(integer=5, string="6") return [prod1, prod2, prod3] + @pytest.fixture def listdict(): - return [{"1": "one", "2": "two", "3": "three"}, - {"4": "four", "5": "five", "6": "six"}, - {"7": "seven", "8": "eight", "9": "nine"}] + return [ + {"1": "one", "2": "two", "3": "three"}, + {"4": "four", "5": "five", "6": "six"}, + {"7": "seven", "8": "eight", "9": "nine"}, + ] + class TestArray(object): def test_empty(self, client): - assert [] == client.array.get_empty() + assert [] == client.array.get_empty() assert client.array.get_null() is None client.array.put_empty([]) def test_boolean_tfft(self, client): - assert [True, False, False, True] == client.array.get_boolean_tfft() + assert [True, False, False, True] == client.array.get_boolean_tfft() client.array.put_boolean_tfft([True, False, False, True]) def test_integer_valid(self, client): - assert [1, -1, 3, 300] == client.array.get_integer_valid() + assert [1, -1, 3, 300] == client.array.get_integer_valid() client.array.put_integer_valid([1, -1, 3, 300]) def test_long_valid(self, client): - assert [1, -1, 3, 300] == client.array.get_long_valid() + assert [1, -1, 3, 300] == client.array.get_long_valid() client.array.put_long_valid([1, -1, 3, 300]) def test_float_valid(self, client): - assert [0, -0.01, -1.2e20] == client.array.get_float_valid() + assert [0, -0.01, -1.2e20] == client.array.get_float_valid() client.array.put_float_valid([0, -0.01, -1.2e20]) def test_double_valid(self, client): - assert [0, -0.01, -1.2e20] == client.array.get_double_valid() + assert [0, -0.01, -1.2e20] == client.array.get_double_valid() client.array.put_double_valid([0, -0.01, -1.2e20]) def test_string_valid(self, client): - assert ["foo1", "foo2", "foo3"] == client.array.get_string_valid() + assert ["foo1", "foo2", "foo3"] == client.array.get_string_valid() client.array.put_string_valid(["foo1", "foo2", "foo3"]) def test_get_string_with_null(self, client): - assert ["foo", None, "foo2"] == client.array.get_string_with_null() + assert ["foo", None, "foo2"] == client.array.get_string_with_null() def test_get_string_with_invalid(self, client): - assert ["foo", "123", "foo2"] == client.array.get_string_with_invalid() + assert ["foo", "123", "foo2"] == client.array.get_string_with_invalid() def test_uuid_valid(self, client): - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"] == client.array.get_uuid_valid() - client.array.put_uuid_valid(["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"]) + assert [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] == client.array.get_uuid_valid() + client.array.put_uuid_valid( + [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] + ) def test_get_uuid_invalid_chars(self, client): - #Handles invalid characters without error because of no guid class - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == client.array.get_uuid_invalid_chars() + # Handles invalid characters without error because of no guid class + assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == client.array.get_uuid_invalid_chars() def test_date_valid(self, client): date1 = isodate.parse_date("2000-12-01") @@ -119,17 +134,17 @@ def test_date_valid(self, client): date3 = isodate.parse_date("1492-10-12") date_array = client.array.get_date_valid() - assert date_array, [date1, date2 == date3] + assert date_array, [date1, date2 == date3] client.array.put_date_valid([date1, date2, date3]) def test_date_time_valid(self, client, datetimes): dt_array = client.array.get_date_time_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] client.array.put_date_time_valid(datetimes) def test_date_time_rfc1123_valid(self, client, datetimes): dt_array = client.array.get_date_time_rfc1123_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] client.array.put_date_time_rfc1123_valid(datetimes) def test_duration_valid(self, client): @@ -137,7 +152,7 @@ def test_duration_valid(self, client): duration2 = timedelta(days=5, hours=1) dur_array = client.array.get_duration_valid() - assert dur_array, [duration1 == duration2] + assert dur_array, [duration1 == duration2] client.array.put_duration_valid([duration1, duration2]) def test_byte_valid(self, client): @@ -148,111 +163,111 @@ def test_byte_valid(self, client): client.array.put_byte_valid([bytes1, bytes2, bytes3]) bytes_array = client.array.get_byte_valid() - assert bytes_array, [bytes1, bytes2 == bytes3] + assert bytes_array, [bytes1, bytes2 == bytes3] def test_get_byte_invalid_null(self, client): bytes_array = client.array.get_byte_invalid_null() - assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] + assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] def test_get_complex_null(self, client): assert client.array.get_complex_null() is None def test_get_complex_empty(self, client): - assert [] == client.array.get_complex_empty() + assert [] == client.array.get_complex_empty() def test_complex_valid(self, client, products): client.array.put_complex_valid(products) - assert products == client.array.get_complex_valid() + assert products == client.array.get_complex_valid() def test_get_array_valid(self, client): listlist = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] client.array.put_array_valid(listlist) - assert listlist == client.array.get_array_valid() + assert listlist == client.array.get_array_valid() def test_dictionary_valid(self, client, listdict): client.array.put_dictionary_valid(listdict) - assert listdict == client.array.get_dictionary_valid() + assert listdict == client.array.get_dictionary_valid() def test_get_complex_item_null(self, client, products): products_null = [products[0], None, products[2]] - assert products_null == client.array.get_complex_item_null() + assert products_null == client.array.get_complex_item_null() def test_get_complex_item_empty(self, client, products): products_empty = [products[0], Product(), products[2]] - assert products_empty == client.array.get_complex_item_empty() + assert products_empty == client.array.get_complex_item_empty() def test_get_array_null(self, client): assert client.array.get_array_null() is None def test_get_array_empty(self, client): - assert [] == client.array.get_array_empty() + assert [] == client.array.get_array_empty() def test_get_array_item_null(self, client): listlist2 = [["1", "2", "3"], None, ["7", "8", "9"]] - assert listlist2 == client.array.get_array_item_null() + assert listlist2 == client.array.get_array_item_null() def test_get_array_item_empty(self, client): listlist3 = [["1", "2", "3"], [], ["7", "8", "9"]] - assert listlist3 == client.array.get_array_item_empty() + assert listlist3 == client.array.get_array_item_empty() def test_get_dictionary_and_dictionary_item_null(self, client, listdict): assert client.array.get_dictionary_null() is None listdict[1] = None - assert listdict == client.array.get_dictionary_item_null() + assert listdict == client.array.get_dictionary_item_null() def test_get_dictionary_and_dictionary_item_empty(self, client, listdict): - assert [] == client.array.get_dictionary_empty() + assert [] == client.array.get_dictionary_empty() listdict[1] = {} - assert listdict == client.array.get_dictionary_item_empty() + assert listdict == client.array.get_dictionary_item_empty() def test_array_get_invalid(self, client): with pytest.raises(DecodeError): client.array.get_invalid() def test_array_get_boolean_invalid_null(self, client): - assert client.array.get_boolean_invalid_null(), [True, None == False] + assert client.array.get_boolean_invalid_null(), [True, None == False] def test_array_get_boolean_invalid_string(self, client): with pytest.raises(DeserializationError): client.array.get_boolean_invalid_string() def test_array_get_int_invalid_null(self, client): - assert client.array.get_int_invalid_null(), [1, None == 0] + assert client.array.get_int_invalid_null(), [1, None == 0] def test_array_get_int_invalid_string(self, client): with pytest.raises(DeserializationError): client.array.get_int_invalid_string() def test_array_get_long_invalid_null(self, client): - assert client.array.get_long_invalid_null(), [1, None == 0] + assert client.array.get_long_invalid_null(), [1, None == 0] def test_array_get_long_invalid_string(self, client): with pytest.raises(DeserializationError): client.array.get_long_invalid_string() def test_array_get_float_invalid_null(self, client): - assert client.array.get_float_invalid_null(), [0.0, None == -1.2e20] + assert client.array.get_float_invalid_null(), [0.0, None == -1.2e20] def test_array_get_float_invalid_string(self, client): with pytest.raises(DeserializationError): client.array.get_float_invalid_string() def test_array_get_double_invalid_null(self, client): - assert client.array.get_double_invalid_null(), [0.0, None == -1.2e20] + assert client.array.get_double_invalid_null(), [0.0, None == -1.2e20] def test_array_get_double_invalid_string(self, client): with pytest.raises(DeserializationError): client.array.get_double_invalid_string() def test_array_get_string_with_invalid(self, client): - assert client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] + assert client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] def test_array_get_date_invalid_null(self, client): d_array = client.array.get_date_invalid_null() - assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] + assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] def test_array_get_date_invalid_chars(self, client): with pytest.raises(DeserializationError): @@ -260,17 +275,19 @@ def test_array_get_date_invalid_chars(self, client): def test_array_get_date_time_invalid_null(self, client): dt_array = client.array.get_date_time_invalid_null() - assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] + assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] def test_array_get_date_time_invalid_chars(self, client): with pytest.raises(DeserializationError): client.array.get_date_time_invalid_chars() def test_array_get_base64_url(self, client): - test_array = ['a string that gets encoded with base64url'.encode(), - 'test string'.encode(), - 'Lorem ipsum'.encode()] - assert client.array.get_base64_url() == test_array + test_array = [ + "a string that gets encoded with base64url".encode(), + "test string".encode(), + "Lorem ipsum".encode(), + ] + assert client.array.get_base64_url() == test_array def test_array_enum_valid(self, client): array = client.array.get_enum_valid() @@ -284,6 +301,7 @@ def test_models(self): from bodyarray.models import Error from bodyarray.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -293,4 +311,5 @@ def test_operation_groups(self): from bodyarray.operations import _array_operations_py3 from bodyarray.operations._array_operations import ArrayOperations as ArrayOperationsPy2 - assert ArrayOperations == ArrayOperationsPy2 \ No newline at end of file + + assert ArrayOperations == ArrayOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_binary.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_binary.py index 229be7dd1a7..a7beb4530cb 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_binary.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_binary.py @@ -28,6 +28,7 @@ from bodybinary import BinaryWithContentTypeApplicationJson from azure.core.exceptions import HttpResponseError + @pytest.fixture def client(): with BinaryWithContentTypeApplicationJson() as client: @@ -37,9 +38,11 @@ def client(): def test_upload_file(client): client.upload.file(json.dumps({"more": "cowbell"})) + def test_upload_binary(client): client.upload.binary(b"Hello, world!") + def test_error(client): with pytest.raises(HttpResponseError): client.download.error_stream() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_bool.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_bool.py index 3e1456a3043..4aa13baefc6 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_bool.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_bool.py @@ -40,11 +40,13 @@ import pytest + @pytest.fixture def client(): with AutoRestBoolTestService(base_url="http://localhost:3000") as client: yield client + class TestBool(object): def test_model_get_true(self, client): @@ -70,6 +72,7 @@ def test_models(self): from bodyboolean.models import Error from bodyboolean.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -79,4 +82,5 @@ def test_operation_groups(self): from bodyboolean.operations import _bool_operations_py3 from bodyboolean.operations._bool_operations import BoolOperations as BoolOperationsPy2 + assert BoolOperations == BoolOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_byte.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_byte.py index ca0ac209bac..58fb3dc5209 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_byte.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_byte.py @@ -40,23 +40,25 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATByteService(base_url="http://localhost:3000") as client: yield client + class TestByte(object): def test_non_ascii(self, client): tests = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x0FB, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) client.byte.put_non_ascii(tests) - assert tests == client.byte.get_non_ascii() + assert tests == client.byte.get_non_ascii() def test_get_null(self, client): assert client.byte.get_null() is None def test_get_empty(self, client): - assert bytearray() == client.byte.get_empty() + assert bytearray() == client.byte.get_empty() def test_get_invalid(self, client): with pytest.raises(DeserializationError): @@ -66,6 +68,7 @@ def test_models(self): from bodybyte.models import Error from bodybyte.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -75,4 +78,5 @@ def test_operation_groups(self): from bodybyte.operations import _byte_operations_py3 from bodybyte.operations._byte_operations import ByteOperations as ByteOperationsPy2 + assert ByteOperations == ByteOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_client_enum.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_client_enum.py index 508bea0234b..cab2e0facec 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_client_enum.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_client_enum.py @@ -26,10 +26,12 @@ import pytest from clientenum import ClientWithEnum, models + @pytest.fixture def client(): with ClientWithEnum(x_ms_enum=models.Enum0.SINGLE) as client: yield client + def test_head(client): client.head() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_complex.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_complex.py index 002c4b48533..fbffc936e17 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_complex.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_complex.py @@ -41,41 +41,46 @@ from bodycomplex import AutoRestComplexTestService from bodycomplex.models import * + class UTC(tzinfo): - def utcoffset(self,dt): - return timedelta(hours=0,minutes=0) + def utcoffset(self, dt): + return timedelta(hours=0, minutes=0) - def tzname(self,dt): + def tzname(self, dt): return "Z" - def dst(self,dt): + def dst(self, dt): return timedelta(0) + import pytest + @pytest.fixture def client(): with AutoRestComplexTestService(base_url="http://localhost:3000") as client: yield client + @pytest.fixture def min_date(): min_date = datetime.min return min_date.replace(tzinfo=UTC()) + class TestComplex(object): def test_basic_get_and_put_valid(self, client): # GET basic/valid basic_result = client.basic.get_valid() - assert 2 == basic_result.id - assert "abc" == basic_result.name - assert CMYKColors.yellow.value == basic_result.color + assert 2 == basic_result.id + assert "abc" == basic_result.name + assert CMYKColors.yellow.value == basic_result.color # PUT basic/valid - basic_result = Basic(id=2, name='abc', color="Magenta") + basic_result = Basic(id=2, name="abc", color="Magenta") client.basic.put_valid(basic_result) - basic_result = Basic(id=2, name='abc', color=CMYKColors.magenta) + basic_result = Basic(id=2, name="abc", color=CMYKColors.magenta) client.basic.put_valid(basic_result) def test_basic_get_empty(self, client): @@ -104,28 +109,28 @@ def test_basic_get_invalid(self, client): def test_primitive_get_and_put_int(self, client): # GET primitive/integer intResult = client.primitive.get_int() - assert -1 == intResult.field1 - assert 2 == intResult.field2 + assert -1 == intResult.field1 + assert 2 == intResult.field2 # PUT primitive/integer - intRequest = {'field1':-1, 'field2':2} + intRequest = {"field1": -1, "field2": 2} client.primitive.put_int(intRequest) def test_primitive_get_and_put_long(self, client): # GET primitive/long longResult = client.primitive.get_long() - assert 1099511627775 == longResult.field1 - assert -999511627788 == longResult.field2 + assert 1099511627775 == longResult.field1 + assert -999511627788 == longResult.field2 # PUT primitive/long - longRequest = {'field1':1099511627775, 'field2':-999511627788} + longRequest = {"field1": 1099511627775, "field2": -999511627788} client.primitive.put_long(longRequest) def test_primitive_get_and_put_float(self, client): # GET primitive/float floatResult = client.primitive.get_float() - assert 1.05 == floatResult.field1 - assert -0.003 == floatResult.field2 + assert 1.05 == floatResult.field1 + assert -0.003 == floatResult.field2 # PUT primitive/float floatRequest = FloatWrapper(field1=1.05, field2=-0.003) @@ -134,12 +139,17 @@ def test_primitive_get_and_put_float(self, client): def test_primitive_get_and_put_double(self, client): # GET primitive/double doubleResult = client.primitive.get_double() - assert 3e-100 == doubleResult.field1 - assert -5e-57 == doubleResult.field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose + assert 3e-100 == doubleResult.field1 + assert ( + -5e-57 + == doubleResult.field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose + ) # PUT primitive/double - doubleRequest = {'field1':3e-100} - doubleRequest['field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose'] = -5e-57 + doubleRequest = {"field1": 3e-100} + doubleRequest[ + "field56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose" + ] = -5e-57 client.primitive.put_double(doubleRequest) def test_primitive_get_and_put_bool(self, client): @@ -155,8 +165,8 @@ def test_primitive_get_and_put_bool(self, client): def test_primitive_get_and_put_string(self, client): # GET primitive/string stringResult = client.primitive.get_string() - assert "goodrequest" == stringResult.field - assert "" == stringResult.empty + assert "goodrequest" == stringResult.field + assert "" == stringResult.empty assert stringResult.null is None # PUT primitive/string @@ -166,23 +176,21 @@ def test_primitive_get_and_put_string(self, client): def test_primitive_get_and_put_date(self, client): # GET primitive/date dateResult = client.primitive.get_date() - assert isodate.parse_date("0001-01-01") == dateResult.field - assert isodate.parse_date("2016-02-29") == dateResult.leap + assert isodate.parse_date("0001-01-01") == dateResult.field + assert isodate.parse_date("2016-02-29") == dateResult.leap - dateRequest = DateWrapper( - field=isodate.parse_date('0001-01-01'), - leap=isodate.parse_date('2016-02-29')) + dateRequest = DateWrapper(field=isodate.parse_date("0001-01-01"), leap=isodate.parse_date("2016-02-29")) client.primitive.put_date(dateRequest) def test_primitive_get_and_put_date_time(self, client, min_date): # GET primitive/datetime datetimeResult = client.primitive.get_date_time() - assert min_date == datetimeResult.field + assert min_date == datetimeResult.field datetime_request = DatetimeWrapper( - field=isodate.parse_datetime("0001-01-01T00:00:00Z"), - now=isodate.parse_datetime("2015-05-18T18:38:00Z")) + field=isodate.parse_datetime("0001-01-01T00:00:00Z"), now=isodate.parse_datetime("2015-05-18T18:38:00Z") + ) client.primitive.put_date_time(datetime_request) def test_primitive_get_and_put_date_time_rfc1123(self, client): @@ -192,18 +200,18 @@ def test_primitive_get_and_put_date_time_rfc1123(self, client): # we are not using the min date of year 1 because of the latest msrest update # with msrest update, minimal year we can parse is 100, instead of 1 min_date = datetime(2001, 1, 1) - assert min_date.replace(tzinfo=UTC()) == datetimeRfc1123Result.field + assert min_date.replace(tzinfo=UTC()) == datetimeRfc1123Result.field # we can still model year 1 though with the latest msrest update datetime_request = Datetimerfc1123Wrapper( - field=isodate.parse_datetime("0001-01-01T00:00:00Z"), - now=isodate.parse_datetime("2015-05-18T11:38:00Z")) + field=isodate.parse_datetime("0001-01-01T00:00:00Z"), now=isodate.parse_datetime("2015-05-18T11:38:00Z") + ) client.primitive.put_date_time_rfc1123(datetime_request) def test_primitive_get_and_put_duration(self, client): # GET primitive/duration expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - assert expected == client.primitive.get_duration().field + assert expected == client.primitive.get_duration().field client.primitive.put_duration(expected) @@ -211,7 +219,7 @@ def test_primitive_get_and_put_byte(self, client): # GET primitive/byte byteResult = client.primitive.get_byte() valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - assert valid_bytes == byteResult.field + assert valid_bytes == byteResult.field # PUT primitive/byte client.primitive.put_byte(valid_bytes) @@ -221,9 +229,9 @@ def test_primitive_get_and_put_byte(self, client): def test_readonlyproperty_get_and_put_valid(self, client): # GET readonly/valid valid_obj = ReadonlyObj(size=2) - valid_obj.id = '1234' + valid_obj.id = "1234" readonly_result = client.readonlyproperty.get_valid() - assert readonly_result == valid_obj + assert readonly_result == valid_obj # PUT readonly/valid readonly_result = client.readonlyproperty.put_valid(2) @@ -234,11 +242,10 @@ def test_readonlyproperty_get_and_put_valid(self, client): def test_array_get_and_put_valid(self, client): # GET array/valid array_result = client.array.get_valid() - assert 5 == len(array_result.array) + assert 5 == len(array_result.array) - array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", - "The quick brown fox jumps over the lazy dog"] - assert array_result.array == array_value + array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", "The quick brown fox jumps over the lazy dog"] + assert array_result.array == array_value # PUT array/valid client.array.put_valid(array_value) @@ -247,7 +254,7 @@ def test_array_get_and_put_empty(self, client): # GET array/empty array_result = client.array.get_empty() - assert 0 == len(array_result.array) + assert 0 == len(array_result.array) # PUT array/empty client.array.put_empty([]) @@ -261,10 +268,10 @@ def test_array_get_not_provided(self, client): def test_dictionary_get_and_put_valid(self, client): # GET dictionary/valid dict_result = client.dictionary.get_valid() - assert 5 == len(dict_result.default_program) + assert 5 == len(dict_result.default_program) - dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} - assert dict_val == dict_result.default_program + dict_val = {"txt": "notepad", "bmp": "mspaint", "xls": "excel", "exe": "", "": None} + assert dict_val == dict_result.default_program # PUT dictionary/valid client.dictionary.put_valid(dict_val) @@ -272,7 +279,7 @@ def test_dictionary_get_and_put_valid(self, client): def test_dictionary_get_and_put_empty(self, client): # GET dictionary/empty dict_result = client.dictionary.get_empty() - assert 0 == len(dict_result.default_program) + assert 0 == len(dict_result.default_program) # PUT dictionary/empty client.dictionary.put_empty(default_program={}) @@ -290,20 +297,19 @@ def test_dictionary_get_not_provided(self, client): def test_inheritance_get_and_put_valid(self, client): # GET inheritance/valid inheritanceResult = client.inheritance.get_valid() - assert 2 == inheritanceResult.id - assert "Siameeee" == inheritanceResult.name - assert -1 == inheritanceResult.hates[1].id - assert "Tomato" == inheritanceResult.hates[1].name + assert 2 == inheritanceResult.id + assert "Siameeee" == inheritanceResult.name + assert -1 == inheritanceResult.hates[1].id + assert "Tomato" == inheritanceResult.hates[1].name # PUT inheritance/valid request = { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [Dog(id=1, name="Potato", food="tomato"), - Dog(id=-1, name="Tomato", food="french fries")] - } + "id": 2, + "name": "Siameeee", + "color": "green", + "breed": "persian", + "hates": [Dog(id=1, name="Potato", food="tomato"), Dog(id=-1, name="Tomato", food="french fries")], + } client.inheritance.put_valid(request) # COMPLEX TYPES THAT INVOLVE POLYMORPHISM @@ -320,46 +326,55 @@ def test_polymorphism_get_and_put_valid(self, client): # GET polymorphism/valid result = client.polymorphism.get_valid() assert result is not None - assert result.location == "alaska" - assert len(result.siblings) == 3 - assert isinstance(result.siblings[0], Shark) - assert isinstance(result.siblings[1], Sawshark) - assert isinstance(result.siblings[2], Goblinshark) - assert result.siblings[0].age == 6 - assert result.siblings[1].age == 105 - assert result.siblings[2].age == 1 - + assert result.location == "alaska" + assert len(result.siblings) == 3 + assert isinstance(result.siblings[0], Shark) + assert isinstance(result.siblings[1], Sawshark) + assert isinstance(result.siblings[2], Goblinshark) + assert result.siblings[0].age == 6 + assert result.siblings[1].age == 105 + assert result.siblings[2].age == 1 # PUT polymorphism/valid - request = Salmon(length=1, - iswild = True, - location = "alaska", - species = "king", - siblings = [Shark(length=20, - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), - age=6, species="predator"), - Sawshark(length=10, - birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - age=105, species="dangerous", - picture=bytearray([255, 255, 255, 255, 254])), - Goblinshark(length=30, - birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), - age=1, species="scary", jawsize=5, color='pinkish-gray')] - ) + request = Salmon( + length=1, + iswild=True, + location="alaska", + species="king", + siblings=[ + Shark(length=20, birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), age=6, species="predator"), + Sawshark( + length=10, + birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), + age=105, + species="dangerous", + picture=bytearray([255, 255, 255, 255, 254]), + ), + Goblinshark( + length=30, + birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), + age=1, + species="scary", + jawsize=5, + color="pinkish-gray", + ), + ], + ) client.polymorphism.put_valid(request) def test_polymorphism_put_valid_missing_required(self, client): - bad_request = Salmon(length=1, + bad_request = Salmon( + length=1, iswild=True, location="alaska", species="king", - siblings = [ - Shark(length=20, - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), - age=6, species="predator"), - Sawshark(length=10, birthday=None, age=105, species="dangerous", - picture=bytearray([255, 255, 255, 255, 254]))] - ) + siblings=[ + Shark(length=20, birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), age=6, species="predator"), + Sawshark( + length=10, birthday=None, age=105, species="dangerous", picture=bytearray([255, 255, 255, 255, 254]) + ), + ], + ) with pytest.raises(ValidationError): client.polymorphism.put_valid_missing_required(bad_request) @@ -369,10 +384,10 @@ def test_polymorphism_put_valid_missing_required(self, client): def test_polymorphismrecursive_get_and_put_valid(self, client): # GET polymorphicrecursive/valid result = client.polymorphicrecursive.get_valid() - assert isinstance(result, Salmon) - assert isinstance(result.siblings[0], Shark) - assert isinstance(result.siblings[0].siblings[0], Salmon) - assert result.siblings[0].siblings[0].location == "atlantic" + assert isinstance(result, Salmon) + assert isinstance(result.siblings[0], Shark) + assert isinstance(result.siblings[0].siblings[0], Salmon) + assert result.siblings[0].siblings[0].location == "atlantic" request = Salmon( iswild=True, @@ -395,28 +410,38 @@ def test_polymorphismrecursive_get_and_put_valid(self, client): age=6, length=20, species="predator", - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z")), + birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), + ), Sawshark( age=105, length=10, species="dangerous", birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]))]), + picture=bytearray([255, 255, 255, 255, 254]), + ), + ], + ), Sawshark( age=105, length=10, species="dangerous", siblings=[], birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]))], - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z")), + picture=bytearray([255, 255, 255, 255, 254]), + ), + ], + birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), + ), Sawshark( age=105, length=10, species="dangerous", siblings=[], birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]))]) + picture=bytearray([255, 255, 255, 255, 254]), + ), + ], + ) # PUT polymorphicrecursive/valid client.polymorphicrecursive.put_valid(request) @@ -433,7 +458,6 @@ def test_polymorphismrecursive_put_valid_stream(self, client): with open(path, "rb") as fd: client.polymorphicrecursive.put_valid(fd) - # Complex types that uses additional properties and polymorphism def test_polymorphism_get_and_put_complicated(self, client): smart_salmon = client.polymorphism.get_complicated() @@ -444,28 +468,27 @@ def test_polymorphism_get_and_put_complicated(self, client): def test_polymorphism_get_and_put_missing_discriminator(self, client): regular_salmon = Salmon( iswild=True, - location='alaska', - species='king', + location="alaska", + species="king", length=1.0, - siblings=[Shark( - age=6, - birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), - length=20, - species='predator' - ), Sawshark( - age=105, - length=10, - species="dangerous", - birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), - picture=bytearray([255, 255, 255, 255, 254]) - ), Goblinshark( - length=30, - birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), - age=1, - species="scary", - jawsize=5, - color='pinkish-gray' - )] + siblings=[ + Shark(age=6, birthday=isodate.parse_datetime("2012-01-05T01:00:00Z"), length=20, species="predator"), + Sawshark( + age=105, + length=10, + species="dangerous", + birthday=isodate.parse_datetime("1900-01-05T01:00:00Z"), + picture=bytearray([255, 255, 255, 255, 254]), + ), + Goblinshark( + length=30, + birthday=isodate.parse_datetime("2015-08-08T00:00:00Z"), + age=1, + species="scary", + jawsize=5, + color="pinkish-gray", + ), + ], ) # Not raise is enough of a test client.polymorphism.put_missing_discriminator(regular_salmon) @@ -479,6 +502,7 @@ def test_models(self): from bodycomplex.models import Error from bodycomplex.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -487,7 +511,10 @@ def test_operation_groups(self): with pytest.raises(ImportError): from bodycomplex.operations import _polymorphicrecursive_operations_py3 - from bodycomplex.operations._polymorphicrecursive_operations import PolymorphicrecursiveOperations as PolymorphicrecursiveOperationsPy2 + from bodycomplex.operations._polymorphicrecursive_operations import ( + PolymorphicrecursiveOperations as PolymorphicrecursiveOperationsPy2, + ) + assert PolymorphicrecursiveOperations == PolymorphicrecursiveOperationsPy2 def test_pass_in_api_version(self, client): @@ -497,15 +524,16 @@ def test_pass_in_api_version(self, client): def test_client_api_version(self): api_version = "2021-10-01" + def check_api_version(pipeline_request): assert pipeline_request.http_request.query["api-version"] == api_version + client = AutoRestComplexTestService( - api_version=api_version, - policies=[CustomHookPolicy(raw_request_hook=check_api_version)] + api_version=api_version, policies=[CustomHookPolicy(raw_request_hook=check_api_version)] ) # PUT basic/valid - basic_result = Basic(id=2, name='abc', color="Magenta") + basic_result = Basic(id=2, name="abc", color="Magenta") client.basic.put_valid(basic_result) # it shall raise exception since we override api_version diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_config.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_config.py index 9d05f27a109..e8f29a51a5c 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_config.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_config.py @@ -26,18 +26,24 @@ from azure.core.pipeline.policies import HttpLoggingPolicy from bodystring import AutoRestSwaggerBATService + class TestConfig(object): def test_http_logging_policy_default(self): with AutoRestSwaggerBATService(base_url="http://localhost:3000") as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + assert ( + client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + ) def test_http_logging_policy_custom(self): http_logging_policy = HttpLoggingPolicy(base_url="test") http_logging_policy = HttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) - with AutoRestSwaggerBATService(base_url="http://localhost:3000", http_logging_policy=http_logging_policy) as client: + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) + with AutoRestSwaggerBATService( + base_url="http://localhost:3000", http_logging_policy=http_logging_policy + ) as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_constants.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_constants.py index 0817b21f867..258f5085d90 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_constants.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_constants.py @@ -27,27 +27,27 @@ from constants import AutoRestSwaggerConstantService from constants import models + @pytest.fixture def client(): with AutoRestSwaggerConstantService(base_url="http://localhost:3000") as client: yield client + def test_put_client_constants(client): client.contants.put_client_constants() assert client._config.header_constant == True assert client._config.query_constant == 100 assert client._config.path_constant == "path" + def test_put_client_constants_override(): - with AutoRestSwaggerConstantService( - header_constant=False, - query_constant=0, - path_constant="new_path" - ) as client: + with AutoRestSwaggerConstantService(header_constant=False, query_constant=0, path_constant="new_path") as client: assert client._config.header_constant == False assert client._config.query_constant == 0 assert client._config.path_constant == "new_path" + def test_models(): assert models.ModelAsStringNoRequiredOneValueDefault().parameter == "value1" assert models.ModelAsStringNoRequiredTwoValueDefault().parameter == "value1" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_custom_base_uri.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_custom_base_uri.py index 88266956e1e..2c911c52272 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_custom_base_uri.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_custom_base_uri.py @@ -41,11 +41,13 @@ import pytest + @pytest.fixture def client(): - with AutoRestParameterizedHostTestClient("host:3000", retry_total = 0) as client: + with AutoRestParameterizedHostTestClient("host:3000", retry_total=0) as client: yield client + class TestCustomBaseUri(object): def test_positive(self): @@ -61,7 +63,7 @@ def test_get_empty_with_none(self, client): client.paths.get_empty(None) def test_get_empty_from_bad_host(self): - with AutoRestParameterizedHostTestClient("badhost:3000", retry_total = 0) as client: + with AutoRestParameterizedHostTestClient("badhost:3000", retry_total=0) as client: with pytest.raises(ServiceRequestError): client.paths.get_empty("local") @@ -73,6 +75,7 @@ def test_models(self): from custombaseurl.models import Error from custombaseurl.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -82,4 +85,5 @@ def test_operation_groups(self): from custombaseurl.operations import _paths_operations_py3 from custombaseurl.operations._paths_operations import PathsOperations as PathsOperationsPy2 + assert PathsOperations == PathsOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_date.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_date.py index 46a7e8485c4..01e661417ff 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_date.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_date.py @@ -40,22 +40,24 @@ import pytest + @pytest.fixture def client(): with AutoRestDateTestService(base_url="http://localhost:3000") as client: yield client + class TestDate(object): def test_model_get_and_put_max_date(self, client): max_date = isodate.parse_date("9999-12-31T23:59:59.999999Z") client.date.put_max_date(max_date) - assert max_date == client.date.get_max_date() + assert max_date == client.date.get_max_date() def test_model_get_and_put_min_date(self, client): min_date = isodate.parse_date("0001-01-01T00:00:00Z") client.date.put_min_date(min_date) - assert min_date == client.date.get_min_date() + assert min_date == client.date.get_min_date() def test_model_get_null(self, client): assert client.date.get_null() is None @@ -76,6 +78,7 @@ def test_models(self): from bodydate.models import Error from bodydate.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -85,4 +88,5 @@ def test_operation_groups(self): from bodydate.operations import _date_operations_py3 from bodydate.operations._date_operations import DateOperations as DateOperationsPy2 + assert DateOperations == DateOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime.py index 0f1d460fb8f..1e99b70c2ac 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime.py @@ -40,19 +40,21 @@ import pytest + @pytest.fixture def client(): with AutoRestDateTimeTestService(base_url="http://localhost:3000") as client: yield client + class TestDatetime(object): def test_utc_max_date_time(self, client): max_date = isodate.parse_datetime("9999-12-31T23:59:59.999Z") dt = client.datetime.get_utc_lowercase_max_date_time() - assert dt == max_date + assert dt == max_date dt = client.datetime.get_utc_uppercase_max_date_time() - assert dt == max_date + assert dt == max_date client.datetime.put_utc_max_date_time(max_date) def test_utc_max_date_time_7digits(self, client): @@ -66,13 +68,12 @@ def test_utc_max_date_time_7digits(self, client): def test_get_utc_min_date_time(self, client): min_date = isodate.parse_datetime("0001-01-01T00:00:00Z") dt = client.datetime.get_utc_min_date_time() - assert dt == min_date + assert dt == min_date client.datetime.put_utc_min_date_time(min_date) def test_get_local_negative_offset_min_date_time(self, client): client.datetime.get_local_negative_offset_min_date_time() - client.datetime.put_local_negative_offset_min_date_time( - isodate.parse_datetime("0001-01-01T00:00:00-14:00")) + client.datetime.put_local_negative_offset_min_date_time(isodate.parse_datetime("0001-01-01T00:00:00-14:00")) def test_get_local_no_offset_min_date_time(self, client): local_no_offset_min_date_time = isodate.parse_datetime("0001-01-01T00:00:00") @@ -92,14 +93,14 @@ def test_local_positive_offset_min_date_time(self, client): client.datetime.get_local_positive_offset_min_date_time() with pytest.raises(SerializationError): - client.datetime.put_local_positive_offset_min_date_time( - isodate.parse_datetime("0001-01-01T00:00:00+14:00")) + client.datetime.put_local_positive_offset_min_date_time(isodate.parse_datetime("0001-01-01T00:00:00+14:00")) def test_local_positive_offset_max_date_time(self, client): client.datetime.get_local_positive_offset_lowercase_max_date_time() client.datetime.get_local_positive_offset_uppercase_max_date_time() client.datetime.put_local_positive_offset_max_date_time( - isodate.parse_datetime("9999-12-31T23:59:59.999999+14:00")) + isodate.parse_datetime("9999-12-31T23:59:59.999999+14:00") + ) def test_get_null(self, client): client.datetime.get_null() @@ -119,12 +120,14 @@ def test_get_underflow(self, client): def test_put_local_negative_offset_max_date_time(self, client): with pytest.raises(SerializationError): client.datetime.put_local_negative_offset_max_date_time( - isodate.parse_datetime("9999-12-31T23:59:59.999999-14:00")) + isodate.parse_datetime("9999-12-31T23:59:59.999999-14:00") + ) def test_models(self): from bodydatetime.models import Error from bodydatetime.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -134,4 +137,5 @@ def test_operation_groups(self): from bodydatetime.operations._datetime_operations_py3 import DatetimeOperations as DatetimeOperationsPy3 from bodydatetime.operations._datetime_operations import DatetimeOperations as DatetimeOperationsPy2 + assert DatetimeOperations == DatetimeOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime_rfc.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime_rfc.py index fe3eb1db29d..8160021de8d 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime_rfc.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_datetime_rfc.py @@ -40,11 +40,13 @@ import pytest + @pytest.fixture def client(): with AutoRestRFC1123DateTimeTestService(base_url="http://localhost:3000") as client: yield client + class TestDateTimeRfc(object): def test_get_null(self, client): @@ -78,6 +80,7 @@ def test_models(self): from bodydatetimerfc1123.models import Error from bodydatetimerfc1123.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -86,5 +89,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from bodydatetimerfc1123.operations import _datetimerfc1123_operations_py3 - from bodydatetimerfc1123.operations._datetimerfc1123_operations import Datetimerfc1123Operations as Datetimerfc1123OperationsPy2 + from bodydatetimerfc1123.operations._datetimerfc1123_operations import ( + Datetimerfc1123Operations as Datetimerfc1123OperationsPy2, + ) + assert Datetimerfc1123Operations == Datetimerfc1123OperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_dictionary.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_dictionary.py index 4318b9e7b8a..280874a4244 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_dictionary.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_dictionary.py @@ -39,114 +39,115 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATDictionaryService(base_url="http://localhost:3000") as client: yield client + @pytest.fixture def test_dict(): test_product1 = Widget(integer=1, string="2") test_product2 = Widget(integer=3, string="4") test_product3 = Widget(integer=5, string="6") - return {"0":test_product1, "1":test_product2, "2":test_product3} + return {"0": test_product1, "1": test_product2, "2": test_product3} + class TestDictionary(object): # Primitive types def test_boolean_tfft(self, client): - tfft = {"0":True, "1":False, "2":False, "3":True} - assert tfft == client.dictionary.get_boolean_tfft() + tfft = {"0": True, "1": False, "2": False, "3": True} + assert tfft == client.dictionary.get_boolean_tfft() client.dictionary.put_boolean_tfft(tfft) def test_get_boolean_invalid(self, client): - invalid_null_dict = {"0":True, "1":None, "2":False} - assert invalid_null_dict == client.dictionary.get_boolean_invalid_null() + invalid_null_dict = {"0": True, "1": None, "2": False} + assert invalid_null_dict == client.dictionary.get_boolean_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_boolean_invalid_string() def test_integer_valid(self, client): - int_valid = {"0":1, "1":-1, "2":3, "3":300} - assert int_valid == client.dictionary.get_integer_valid() + int_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert int_valid == client.dictionary.get_integer_valid() client.dictionary.put_integer_valid(int_valid) def test_get_int_invalid(self, client): - int_null_dict = {"0":1, "1":None, "2":0} - assert int_null_dict == client.dictionary.get_int_invalid_null() + int_null_dict = {"0": 1, "1": None, "2": 0} + assert int_null_dict == client.dictionary.get_int_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_int_invalid_string() def test_long_valid(self, client): - long_valid = {"0":1, "1":-1, "2":3, "3":300} - assert long_valid == client.dictionary.get_long_valid() + long_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert long_valid == client.dictionary.get_long_valid() client.dictionary.put_long_valid(long_valid) def test_get_long_invalid(self, client): - long_null_dict = {"0":1, "1":None, "2":0} - assert long_null_dict == client.dictionary.get_long_invalid_null() + long_null_dict = {"0": 1, "1": None, "2": 0} + assert long_null_dict == client.dictionary.get_long_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_long_invalid_string() def test_float_valid(self, client): - float_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert float_valid == client.dictionary.get_float_valid() + float_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert float_valid == client.dictionary.get_float_valid() client.dictionary.put_float_valid(float_valid) def test_get_float_invalid(self, client): - float_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert float_null_dict == client.dictionary.get_float_invalid_null() + float_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert float_null_dict == client.dictionary.get_float_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_float_invalid_string() def test_double_valid(self, client): - double_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert double_valid == client.dictionary.get_double_valid() + double_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert double_valid == client.dictionary.get_double_valid() client.dictionary.put_double_valid(double_valid) def test_get_double_invalid(self, client): - double_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert double_null_dict == client.dictionary.get_double_invalid_null() + double_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert double_null_dict == client.dictionary.get_double_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_double_invalid_string() def test_string_valid(self, client): - string_valid = {"0":"foo1", "1":"foo2", "2":"foo3"} - assert string_valid == client.dictionary.get_string_valid() + string_valid = {"0": "foo1", "1": "foo2", "2": "foo3"} + assert string_valid == client.dictionary.get_string_valid() client.dictionary.put_string_valid(string_valid) def test_get_string_with_null_and_invalid(self, client): - string_null_dict = {"0":"foo", "1":None, "2":"foo2"} - string_invalid_dict = {"0":"foo", "1":"123", "2":"foo2"} - assert string_null_dict == client.dictionary.get_string_with_null() - assert string_invalid_dict == client.dictionary.get_string_with_invalid() + string_null_dict = {"0": "foo", "1": None, "2": "foo2"} + string_invalid_dict = {"0": "foo", "1": "123", "2": "foo2"} + assert string_null_dict == client.dictionary.get_string_with_null() + assert string_invalid_dict == client.dictionary.get_string_with_invalid() def test_date_valid(self, client): date1 = isodate.parse_date("2000-12-01T00:00:00Z") date2 = isodate.parse_date("1980-01-02T00:00:00Z") date3 = isodate.parse_date("1492-10-12T00:00:00Z") - valid_date_dict = {"0":date1, "1":date2, "2":date3} + valid_date_dict = {"0": date1, "1": date2, "2": date3} date_dictionary = client.dictionary.get_date_valid() - assert date_dictionary == valid_date_dict + assert date_dictionary == valid_date_dict client.dictionary.put_date_valid(valid_date_dict) def test_get_date_invalid(self, client): - date_null_dict = {"0":isodate.parse_date("2012-01-01"), - "1":None, - "2":isodate.parse_date("1776-07-04")} - assert date_null_dict == client.dictionary.get_date_invalid_null() + date_null_dict = {"0": isodate.parse_date("2012-01-01"), "1": None, "2": isodate.parse_date("1776-07-04")} + assert date_null_dict == client.dictionary.get_date_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_date_invalid_chars() @@ -155,15 +156,15 @@ def test_date_time_valid(self, client): datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") datetime2 = isodate.parse_datetime("1980-01-02T00:11:35+01:00") datetime3 = isodate.parse_datetime("1492-10-12T10:15:01-08:00") - valid_datetime_dict = {"0":datetime1, "1":datetime2, "2":datetime3} + valid_datetime_dict = {"0": datetime1, "1": datetime2, "2": datetime3} - assert valid_datetime_dict == client.dictionary.get_date_time_valid() + assert valid_datetime_dict == client.dictionary.get_date_time_valid() client.dictionary.put_date_time_valid(valid_datetime_dict) def test_get_date_time_invalid(self, client): - datetime_null_dict = {"0":isodate.parse_datetime("2000-12-01T00:00:01Z"), "1":None} - assert datetime_null_dict == client.dictionary.get_date_time_invalid_null() + datetime_null_dict = {"0": isodate.parse_datetime("2000-12-01T00:00:01Z"), "1": None} + assert datetime_null_dict == client.dictionary.get_date_time_invalid_null() with pytest.raises(DeserializationError): client.dictionary.get_date_time_invalid_chars() @@ -172,18 +173,18 @@ def test_date_time_rfc1123_valid(self, client): rfc_datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") rfc_datetime2 = isodate.parse_datetime("1980-01-02T00:11:35Z") rfc_datetime3 = isodate.parse_datetime("1492-10-12T10:15:01Z") - valid_rfc_dict = {"0":rfc_datetime1, "1":rfc_datetime2, "2":rfc_datetime3} + valid_rfc_dict = {"0": rfc_datetime1, "1": rfc_datetime2, "2": rfc_datetime3} - assert valid_rfc_dict == client.dictionary.get_date_time_rfc1123_valid() + assert valid_rfc_dict == client.dictionary.get_date_time_rfc1123_valid() client.dictionary.put_date_time_rfc1123_valid(valid_rfc_dict) def test_get_duration_valid(self, client): duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration2 = timedelta(days=5, hours=1) - valid_duration_dict = {"0":duration1, "1":duration2} + valid_duration_dict = {"0": duration1, "1": duration2} - assert valid_duration_dict == client.dictionary.get_duration_valid() + assert valid_duration_dict == client.dictionary.get_duration_valid() client.dictionary.put_duration_valid(valid_duration_dict) @@ -193,28 +194,30 @@ def test_bytes_valid(self, client): bytes3 = bytearray([0x025, 0x029, 0x043]) bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_valid = {"0":bytes1, "1":bytes2, "2":bytes3} + bytes_valid = {"0": bytes1, "1": bytes2, "2": bytes3} client.dictionary.put_byte_valid(bytes_valid) bytes_result = client.dictionary.get_byte_valid() - assert bytes_valid == bytes_result + assert bytes_valid == bytes_result def test_get_byte_invalid_null(self, client): bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_null = {"0":bytes4, "1":None} + bytes_null = {"0": bytes4, "1": None} bytes_result = client.dictionary.get_byte_invalid_null() - assert bytes_null == bytes_result + assert bytes_null == bytes_result def test_get_base64_url(self, client): - test_dict = {'0': 'a string that gets encoded with base64url'.encode(), - '1': 'test string'.encode(), - '2': 'Lorem ipsum'.encode()} - assert client.dictionary.get_base64_url() == test_dict + test_dict = { + "0": "a string that gets encoded with base64url".encode(), + "1": "test string".encode(), + "2": "Lorem ipsum".encode(), + } + assert client.dictionary.get_base64_url() == test_dict # Basic dictionary parsing def test_empty(self, client): - assert {} == client.dictionary.get_empty() + assert {} == client.dictionary.get_empty() client.dictionary.put_empty({}) @@ -229,85 +232,92 @@ def test_get_null_key_and_value(self, client): # but we fail and we're happy with it. with pytest.raises(DecodeError): client.dictionary.get_null_key() - assert {"key1":None} == client.dictionary.get_null_value() + assert {"key1": None} == client.dictionary.get_null_value() def test_get_empty_string_key(self, client): - assert {"":"val1"} == client.dictionary.get_empty_string_key() + assert {"": "val1"} == client.dictionary.get_empty_string_key() # Dictionary composed types def test_get_complex_null_and_empty(self, client): assert client.dictionary.get_complex_null() is None - assert {} == client.dictionary.get_complex_empty() + assert {} == client.dictionary.get_complex_empty() def test_complex_valid(self, client, test_dict): client.dictionary.put_complex_valid(test_dict) complex_result = client.dictionary.get_complex_valid() - assert test_dict == complex_result + assert test_dict == complex_result def test_array_valid(self, client): - list_dict = {"0":["1","2","3"], "1":["4","5","6"], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", "9"]} client.dictionary.put_array_valid(list_dict) array_result = client.dictionary.get_array_valid() - assert list_dict == array_result + assert list_dict == array_result def test_dictionary_valid(self, client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{"4":"four","5":"five","6":"six"}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": {"4": "four", "5": "five", "6": "six"}, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } client.dictionary.put_dictionary_valid(dict_dict) dict_result = client.dictionary.get_dictionary_valid() - assert dict_dict == dict_result + assert dict_dict == dict_result def test_get_complex_null_and_empty(self, client): assert client.dictionary.get_complex_null() is None - assert {} == client.dictionary.get_complex_empty() + assert {} == client.dictionary.get_complex_empty() def test_get_complex_item_null_and_empty(self, client, test_dict): - test_dict_null = {"0":test_dict["0"], "1":None, "2":test_dict["2"]} + test_dict_null = {"0": test_dict["0"], "1": None, "2": test_dict["2"]} complex_result = client.dictionary.get_complex_item_null() - assert complex_result == test_dict_null + assert complex_result == test_dict_null - test_dict_empty = {"0":test_dict["0"], "1":Widget(), "2":test_dict["2"]} + test_dict_empty = {"0": test_dict["0"], "1": Widget(), "2": test_dict["2"]} complex_result = client.dictionary.get_complex_item_empty() - assert complex_result == test_dict_empty + assert complex_result == test_dict_empty def test_get_array_empty(self, client): assert client.dictionary.get_array_null() is None - assert {} == client.dictionary.get_array_empty() + assert {} == client.dictionary.get_array_empty() def test_get_array_item_null_and_empty(self, client): - list_dict = {"0":["1","2","3"], "1":None, "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": None, "2": ["7", "8", "9"]} array_result = client.dictionary.get_array_item_null() - assert list_dict == array_result + assert list_dict == array_result - list_dict = {"0":["1","2","3"], "1":[], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": [], "2": ["7", "8", "9"]} array_result = client.dictionary.get_array_item_empty() - assert list_dict == array_result + assert list_dict == array_result def test_get_dictionary_null_and_empty(self, client): assert client.dictionary.get_dictionary_null() is None - assert {} == client.dictionary.get_dictionary_empty() + assert {} == client.dictionary.get_dictionary_empty() def test_get_dictionary_item_null_and_empty(self, client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":None, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": None, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } dict_result = client.dictionary.get_dictionary_item_null() - assert dict_dict == dict_result + assert dict_dict == dict_result - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": {}, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } dict_result = client.dictionary.get_dictionary_item_empty() - assert dict_dict == dict_result + assert dict_dict == dict_result def test_models(self): from bodydictionary.models import Error from bodydictionary.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -317,4 +327,5 @@ def test_operation_groups(self): from bodydictionary.operations import _dictionary_operations_py3 from bodydictionary.operations._dictionary_operations import DictionaryOperations as DictionaryOperationsPy2 + assert DictionaryOperations == DictionaryOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_duration.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_duration.py index 2a7151b5e6c..169fc51fc07 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_duration.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_duration.py @@ -40,11 +40,13 @@ import pytest + @pytest.fixture def client(): with AutoRestDurationTestService(base_url="http://localhost:3000") as client: yield client + class TestDuration(object): def test_get_null_and_invalid(self, client): @@ -61,6 +63,7 @@ def test_models(self): from bodyduration.models import Error from bodyduration.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -70,4 +73,5 @@ def test_operation_groups(self): from bodyduration.operations import _duration_operations_py3 from bodyduration.operations._duration_operations import DurationOperations as DurationOperationsPy2 + assert DurationOperations == DurationOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_error_with_secrets.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_error_with_secrets.py index 532d84eb883..2c35ca0d909 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_error_with_secrets.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_error_with_secrets.py @@ -28,6 +28,7 @@ from errorwithsecrets.operations._error_with_secrets_operations import build_create_secret_request from azure.core.exceptions import HttpResponseError + @pytest.fixture def client(): with ErrorWithSecrets() as client: @@ -38,11 +39,12 @@ def test_create_secret(client): request = build_create_secret_request( headers={"authorization": "SharedKey 1c88a67921784300a462b2cb61da2339"}, params={"key": "1c88a67921784300a462b2cb61da2339"}, - json={ "key": "1c88a67921784300a462b2cb61da2339" }, + json={"key": "1c88a67921784300a462b2cb61da2339"}, ) response = client._send_request(request) response.raise_for_status() + def test_raise_error_with_secrets(client): with pytest.raises(HttpResponseError) as ex: client.get_error_with_secrets() diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_extensible_enums.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_extensible_enums.py index aecbb573c89..f52880abaa9 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_extensible_enums.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_extensible_enums.py @@ -38,45 +38,44 @@ import pytest + @pytest.fixture def client(): with PetStoreInc(base_url="http://localhost:3000") as client: yield client + class TestExtensibleEnums(object): def test_get_by_pet_id(self, client): # Now enum return are always string (Autorest.Python 3.0) - tommy = client.pet.get_by_pet_id('tommy') - assert tommy.days_of_week == "Monday" - assert tommy.int_enum == "1" + tommy = client.pet.get_by_pet_id("tommy") + assert tommy.days_of_week == "Monday" + assert tommy.int_enum == "1" - casper = client.pet.get_by_pet_id('casper') - assert casper.days_of_week == "Weekend" - assert casper.int_enum == "2" + casper = client.pet.get_by_pet_id("casper") + assert casper.days_of_week == "Weekend" + assert casper.int_enum == "2" - scooby = client.pet.get_by_pet_id('scooby') - assert scooby.days_of_week == "Thursday" + scooby = client.pet.get_by_pet_id("scooby") + assert scooby.days_of_week == "Thursday" # https://github.com/Azure/autorest.csharp/blob/e5f871b7433e0f6ca6a17307fba4a2cfea4942b4/test/vanilla/AcceptanceTests.cs#L429 # "allowedValues" of "x-ms-enum" is not supported in Python - assert scooby.int_enum == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" + assert scooby.int_enum == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" def test_add_pet(self, client): - retriever = Pet( - name="Retriever", - int_enum=IntEnum.three, - days_of_week=DaysOfWeekExtensibleEnum.friday - ) + retriever = Pet(name="Retriever", int_enum=IntEnum.three, days_of_week=DaysOfWeekExtensibleEnum.friday) returned_pet = client.pet.add_pet(retriever) - assert returned_pet.days_of_week == "Friday" - assert returned_pet.int_enum == "3" - assert returned_pet.name == "Retriever" + assert returned_pet.days_of_week == "Friday" + assert returned_pet.int_enum == "3" + assert returned_pet.name == "Retriever" def test_models(self): from extensibleenumsswagger.models import Pet from extensibleenumsswagger.models._models_py3 import Pet as PetPy3 + assert Pet == PetPy3 def test_operation_groups(self): @@ -86,4 +85,5 @@ def test_operation_groups(self): from extensibleenumsswagger.operations import _pet_operations_py3 from extensibleenumsswagger.operations._pet_operations import PetOperations as PetOperationsPy2 + assert PetOperations == PetOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_file.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_file.py index 24105e58045..72b772d6c27 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_file.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_file.py @@ -44,19 +44,23 @@ @pytest.fixture def client(connection_data_block_size): with AutoRestSwaggerBATFileService( - base_url="http://localhost:3000", connection_data_block_size=connection_data_block_size) as client: + base_url="http://localhost:3000", connection_data_block_size=connection_data_block_size + ) as client: yield client + @pytest.fixture def callback(): def _callback(response, data_stream, headers): assert not data_stream.response.internal_response._content_consumed return data_stream + return _callback + class TestFile(object): - @pytest.mark.parametrize('connection_data_block_size', [1000]) + @pytest.mark.parametrize("connection_data_block_size", [1000]) def test_get_file(self, client): file_length = 0 with io.BytesIO() as file_handle: @@ -67,20 +71,31 @@ def test_get_file(self, client): for data in stream: assert 0 < len(data) <= stream.block_size file_length += len(data) - print("Downloading... {}%".format(int(file_length*100/total))) + print("Downloading... {}%".format(int(file_length * 100 / total))) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) - - with open(sample_file, 'rb') as data: + join( + cwd, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) + + with open(sample_file, "rb") as data: sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) + assert sample_data == hash(file_handle.getvalue()) - @pytest.mark.parametrize('connection_data_block_size', [4096]) + @pytest.mark.parametrize("connection_data_block_size", [4096]) def test_get_empty_file(self, client): file_length = 0 with io.BytesIO() as file_handle: @@ -92,9 +107,9 @@ def test_get_empty_file(self, client): file_length += len(data) file_handle.write(data) - assert file_length == 0 + assert file_length == 0 - @pytest.mark.parametrize('connection_data_block_size', [4096]) + @pytest.mark.parametrize("connection_data_block_size", [4096]) def test_files_long_running(self, client): file_length = 0 stream = client.files.get_file_large() @@ -102,9 +117,9 @@ def test_files_long_running(self, client): assert 0 < len(data) <= stream.block_size file_length += len(data) - assert file_length == 3000 * 1024 * 1024 + assert file_length == 3000 * 1024 * 1024 - @pytest.mark.parametrize('connection_data_block_size', [None]) + @pytest.mark.parametrize("connection_data_block_size", [None]) def test_get_file_with_callback(self, client, callback): file_length = 0 with io.BytesIO() as file_handle: @@ -115,17 +130,28 @@ def test_get_file_with_callback(self, client, callback): file_length += len(data) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) - - with open(sample_file, 'rb') as data: + join( + cwd, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) + + with open(sample_file, "rb") as data: sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) + assert sample_data == hash(file_handle.getvalue()) - @pytest.mark.parametrize('connection_data_block_size', [None]) + @pytest.mark.parametrize("connection_data_block_size", [None]) def test_get_empty_file_with_callback(self, client, callback): file_length = 0 with io.BytesIO() as file_handle: @@ -134,12 +160,13 @@ def test_get_empty_file_with_callback(self, client, callback): file_length += len(data) file_handle.write(data) - assert file_length == 0 + assert file_length == 0 def test_models(self): from bodyfile.models import Error from bodyfile.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -149,4 +176,5 @@ def test_operation_groups(self): from bodyfile.operations import _files_operations_py3 from bodyfile.operations._files_operations import FilesOperations as FilesOperationsPy2 + assert FilesOperations == FilesOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_form_data.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_form_data.py index cdc89e1d582..dd6cd98ebb0 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_form_data.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_form_data.py @@ -33,7 +33,7 @@ from os.path import dirname, pardir, join, realpath cwd = dirname(realpath(__file__)) -log_level = int(os.environ.get('PythonLogLevel', 30)) +log_level = int(os.environ.get("PythonLogLevel", 30)) tests = realpath(join(cwd, pardir, "Expected", "AcceptanceTests")) sys.path.append(join(tests, "BodyFormData")) @@ -43,36 +43,39 @@ import pytest + @pytest.fixture def dummy_file(): - with tempfile.NamedTemporaryFile(mode='w', delete=False) as dummy: + with tempfile.NamedTemporaryFile(mode="w", delete=False) as dummy: dummy.write("Test file") # Get outside of the "with", so file can be re-opened on Windows yield dummy.name os.remove(dummy.name) + @pytest.fixture def client(): with AutoRestSwaggerBATFormDataService( base_url="http://localhost:3000", - connection_data_block_size = 2, - retry_total = 50, # Be agressive on this test, sometimes testserver DDOS :-p - retry_backoff_factor = 1.6 + connection_data_block_size=2, + retry_total=50, # Be agressive on this test, sometimes testserver DDOS :-p + retry_backoff_factor=1.6, ) as client: yield client + class TestFormData(object): def test_file_upload_stream(self, client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = client.formdata.upload_file(stream_data, "UploadFile.txt") for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string def test_file_upload_stream_raw(self, client): @@ -80,23 +83,23 @@ def test_callback(response, data, headers): return data test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: stream = client.formdata.upload_file(stream_data, "UploadFile.txt", cls=test_callback) for data in stream: result.write(data) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string def test_file_upload_file_stream(self, client, dummy_file): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = client.formdata.upload_file(upload_data, name) for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" def test_file_upload_file_stream_raw(self, client, dummy_file): @@ -105,42 +108,42 @@ def test_callback(response, data, headers): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: stream = client.formdata.upload_file(upload_data, name, cls=test_callback) for data in stream: result.write(data) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" def test_file_body_upload(self, client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = client.formdata.upload_file_via_body(stream_data) for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = client.formdata.upload_file_via_body(upload_data) for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" def test_file_body_upload_generator(self, client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") def stream_upload(data, length, block_size): progress = 0 while True: block = data.read(block_size) progress += len(block) - print("Progress... {}%".format(int(progress*100/length))) + print("Progress... {}%".format(int(progress * 100 / length))) if not block: break yield block @@ -151,10 +154,10 @@ def stream_upload(data, length, block_size): resp = client.formdata.upload_file_via_body(streamed_upload) for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: streamed_upload = stream_upload(upload_data, len("Test file"), 2) response = client.formdata.upload_file_via_body(streamed_upload) for data in response: @@ -168,4 +171,5 @@ def test_operation_groups(self): from bodyformdata.operations import _formdata_operations_py3 from bodyformdata.operations._formdata_operations import FormdataOperations as FormdataOperationsPy2 - assert FormdataOperations == FormdataOperationsPy2 \ No newline at end of file + + assert FormdataOperations == FormdataOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_header.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_header.py index 8cfd789bed1..bff38043713 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_header.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_header.py @@ -41,17 +41,21 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATHeaderService(base_url="http://localhost:3000") as client: yield client + @pytest.fixture def value_header(): def _value_header(response, _, headers): return headers.get("value") + return _value_header + class TestHeader(object): def test_integer(self, client, value_header): @@ -114,7 +118,7 @@ def test_string(self, client, value_header): def test_enum(self, client, value_header): client.header.param_enum("valid", GreyscaleColors.grey) - client.header.param_enum("valid", 'GREY') + client.header.param_enum("valid", "GREY") client.header.param_enum("null", None) response = client.header.response_enum("valid", cls=value_header) @@ -165,7 +169,7 @@ def test_duration(self, client, value_header): assert response == timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) def test_byte(self, client, value_header): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") client.header.param_byte("valid", u_bytes) response = client.header.response_byte("valid", cls=value_header) @@ -175,23 +179,26 @@ def test_byte(self, client, value_header): def test_response_existing_key(self, client): def useragent_header(response, _, headers): - return headers.get('User-Agent') + return headers.get("User-Agent") + response = client.header.response_existing_key(cls=useragent_header) assert response == "overwrite" def test_response_protected_key(self, client): # This test is only valid for C#, which content-type can't be override this way - #client.header.param_protected_key("text/html") + # client.header.param_protected_key("text/html") # This test has different result compare to C#, which content-type is saved in another place. def content_header(response, _, headers): - return headers.get('Content-Type') + return headers.get("Content-Type") + response = client.header.response_protected_key(cls=content_header) assert response == "text/html; charset=utf-8" def test_custom_request_id(self, client): def status_code(pipeline_response, _, headers): return pipeline_response.http_response.status_code + custom_headers = {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} response = client.header.custom_request_id(headers=custom_headers, cls=status_code) assert response == 200 @@ -200,6 +207,7 @@ def test_models(self): from header.models import Error from header.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -209,4 +217,5 @@ def test_operation_groups(self): from header.operations import _header_operations_py3 from header.operations._header_operations import HeaderOperations as HeaderOperationsPy2 + assert HeaderOperations == HeaderOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_hooks.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_hooks.py index bb127eadfb3..28835c798e9 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_hooks.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_hooks.py @@ -27,25 +27,30 @@ from azure.core.pipeline.policies import CustomHookPolicy from bodyarray import AutoRestSwaggerBATArrayService + def is_rest(obj): return hasattr(obj, "content") + def test_raw_request_hook(): def _callback(request): assert not is_rest(request.http_request) assert hasattr(request.http_request, "set_multipart_mixed") raise ValueError("I entered the callback!") + raw_request_hook_policy = CustomHookPolicy(raw_request_hook=_callback) client = AutoRestSwaggerBATArrayService(policies=[raw_request_hook_policy]) with pytest.raises(ValueError) as ex: client.array.get_array_empty() assert "I entered the callback!" in str(ex.value) + def test_raw_response_hook(): def _callback(response): assert not is_rest(response.http_response) assert hasattr(response.http_response, "parts") raise ValueError("I entered the callback!") + raw_response_hook_policy = CustomHookPolicy(raw_response_hook=_callback) client = AutoRestSwaggerBATArrayService(policies=[raw_response_hook_policy]) with pytest.raises(ValueError) as ex: diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_http.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_http.py index ccd720891dc..c5554122649 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_http.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_http.py @@ -49,13 +49,7 @@ @pytest.fixture() def client(cookie_policy): """Create a AutoRestHttpInfrastructureTestService client with test server credentials.""" - policies = [ - HeadersPolicy(), - ContentDecodePolicy(), - RedirectPolicy(), - RetryPolicy(), - cookie_policy - ] + policies = [HeadersPolicy(), ContentDecodePolicy(), RedirectPolicy(), RetryPolicy(), cookie_policy] with AutoRestHttpInfrastructureTestService(base_url="http://localhost:3000", policies=policies) as client: yield client @@ -66,7 +60,8 @@ def assert_status(self, code, func, *args, **kwargs): def return_status(pipeline_response, data, headers): assert isinstance(pipeline_response, PipelineResponse) return pipeline_response.http_response.status_code - kwargs['cls'] = return_status + + kwargs["cls"] = return_status status_code = func(*args, **kwargs) assert status_code == code @@ -119,61 +114,61 @@ def assert_raises_with_status_and_response_contains(self, code, msg, func, *args def test_get200_model204(self, client): r = client.multiple_responses.get200_model204_no_model_default_error200_valid() - assert '200' == r.status_code + assert "200" == r.status_code - self.assert_raises_with_status(201, - client.multiple_responses.get200_model204_no_model_default_error201_invalid) + self.assert_raises_with_status(201, client.multiple_responses.get200_model204_no_model_default_error201_invalid) - self.assert_raises_with_status(202, - client.multiple_responses.get200_model204_no_model_default_error202_none) + self.assert_raises_with_status(202, client.multiple_responses.get200_model204_no_model_default_error202_none) assert client.multiple_responses.get200_model204_no_model_default_error204_valid() is None - self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model204_no_model_default_error400_valid) + self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model204_no_model_default_error400_valid + ) def test_get200_model201(self, client): self.assert_status(200, client.multiple_responses.get200_model201_model_default_error200_valid) b_model = client.multiple_responses.get200_model201_model_default_error201_valid() assert b_model is not None - assert b_model.status_code == "201" - assert b_model.text_status_code == "Created" + assert b_model.status_code == "201" + assert b_model.text_status_code == "Created" - self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model201_model_default_error400_valid) + self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model201_model_default_error400_valid + ) def test_get200_model_a201_model_c404(self, client): a_model = client.multiple_responses.get200_model_a201_model_c404_model_d_default_error200_valid() assert a_model is not None - assert a_model.status_code == "200" + assert a_model.status_code == "200" c_model = client.multiple_responses.get200_model_a201_model_c404_model_d_default_error201_valid() assert c_model is not None - assert c_model.http_code == "201" + assert c_model.http_code == "201" d_model = client.multiple_responses.get200_model_a201_model_c404_model_d_default_error404_valid() assert d_model is not None - assert d_model.http_status_code == "404" + assert d_model.http_status_code == "404" - self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid) + self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid + ) def test_get202_none204(self, client): client.multiple_responses.get202_none204_none_default_error202_none() client.multiple_responses.get202_none204_none_default_error204_none() - self.assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get202_none204_none_default_error400_valid) + self.assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get202_none204_none_default_error400_valid + ) client.multiple_responses.get202_none204_none_default_none202_invalid() client.multiple_responses.get202_none204_none_default_none204_none() - self.assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_none) + self.assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_none) - self.assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_invalid) + self.assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_invalid) def test_get_default_model_a200(self, client): self.assert_status(200, client.multiple_responses.get_default_model_a200_valid) @@ -183,22 +178,18 @@ def test_get_default_model_a200(self, client): client.multiple_responses.get_default_model_a200_none() def test_get_default_model_a400(self, client): - self.assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_valid) + self.assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_valid) - self.assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_none) + self.assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_none) def test_get_default_none200(self, client): client.multiple_responses.get_default_none200_invalid() client.multiple_responses.get_default_none200_none() def test_get_default_none400(self, client): - self.assert_raises_with_status(400, - client.multiple_responses.get_default_none400_invalid) + self.assert_raises_with_status(400, client.multiple_responses.get_default_none400_invalid) - self.assert_raises_with_status(400, - client.multiple_responses.get_default_none400_none) + self.assert_raises_with_status(400, client.multiple_responses.get_default_none400_none) def test_get200_model_a200(self, client): assert client.multiple_responses.get200_model_a200_none() is None @@ -208,31 +199,23 @@ def test_get200_model_a200(self, client): assert client.multiple_responses.get200_model_a200_invalid().status_code is None def test_get200_model_a400(self, client): - self.assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_none) - self.assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_valid) - self.assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_invalid) + self.assert_raises_with_status(400, client.multiple_responses.get200_model_a400_none) + self.assert_raises_with_status(400, client.multiple_responses.get200_model_a400_valid) + self.assert_raises_with_status(400, client.multiple_responses.get200_model_a400_invalid) def test_get200_model_a202(self, client): - self.assert_raises_with_status(202, - client.multiple_responses.get200_model_a202_valid) + self.assert_raises_with_status(202, client.multiple_responses.get200_model_a202_valid) def test_server_error_status_codes_501(self, client): - self.assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.head501) + self.assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.head501) - self.assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.get501) + self.assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.get501) def test_server_error_status_codes_505(self, client): - self.assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.post505) + self.assert_raises_with_status(requests.codes.http_version_not_supported, client.http_server_failure.post505) - self.assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.delete505) + self.assert_raises_with_status(requests.codes.http_version_not_supported, client.http_server_failure.delete505) def test_retry_status_codes_408(self, client): client.http_retry.head408() @@ -254,96 +237,77 @@ def test_retry_status_codes_504(self, client): client.http_retry.patch504() def test_error_status_codes_400(self, client): - self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.head400) + self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.head400) - self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.get400) + self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.get400) # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.bad_request, + # self.assert_raises_with_status(requests.codes.bad_request, # client.http_client_failure.options400) - self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.put400) + self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.put400) - self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.patch400) + self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.patch400) - self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.post400) + self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.post400) - self.assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.delete400) + self.assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.delete400) def test_error_status_codes_401(self, client): - self.assert_raises_with_status(requests.codes.unauthorized, - client.http_client_failure.head401) + self.assert_raises_with_status(requests.codes.unauthorized, client.http_client_failure.head401) def test_error_status_codes_402(self, client): - self.assert_raises_with_status(requests.codes.payment_required, - client.http_client_failure.get402) + self.assert_raises_with_status(requests.codes.payment_required, client.http_client_failure.get402) def test_error_status_codes_403(self, client): # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.forbidden, + # self.assert_raises_with_status(requests.codes.forbidden, # client.http_client_failure.options403) - self.assert_raises_with_status(requests.codes.forbidden, - client.http_client_failure.get403) + self.assert_raises_with_status(requests.codes.forbidden, client.http_client_failure.get403) def test_error_status_codes_404(self, client): - self.assert_raises_with_status(requests.codes.not_found, - client.http_client_failure.put404) + self.assert_raises_with_status(requests.codes.not_found, client.http_client_failure.put404) def test_error_status_codes_405(self, client): - self.assert_raises_with_status(requests.codes.method_not_allowed, - client.http_client_failure.patch405) + self.assert_raises_with_status(requests.codes.method_not_allowed, client.http_client_failure.patch405) def test_error_status_codes_406(self, client): - self.assert_raises_with_status(requests.codes.not_acceptable, - client.http_client_failure.post406) + self.assert_raises_with_status(requests.codes.not_acceptable, client.http_client_failure.post406) def test_error_status_codes_407(self, client): - self.assert_raises_with_status(requests.codes.proxy_authentication_required, - client.http_client_failure.delete407) + self.assert_raises_with_status( + requests.codes.proxy_authentication_required, client.http_client_failure.delete407 + ) def test_error_status_codes_409(self, client): - self.assert_raises_with_status(requests.codes.conflict, - client.http_client_failure.put409) + self.assert_raises_with_status(requests.codes.conflict, client.http_client_failure.put409) def test_error_status_codes_410(self, client): - self.assert_raises_with_status(requests.codes.gone, - client.http_client_failure.head410) + self.assert_raises_with_status(requests.codes.gone, client.http_client_failure.head410) def test_error_status_codes_411(self, client): - self.assert_raises_with_status(requests.codes.length_required, - client.http_client_failure.get411) + self.assert_raises_with_status(requests.codes.length_required, client.http_client_failure.get411) # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.precondition_failed, + # self.assert_raises_with_status(requests.codes.precondition_failed, # client.http_client_failure.options412) - self.assert_raises_with_status(requests.codes.precondition_failed, - client.http_client_failure.get412) + self.assert_raises_with_status(requests.codes.precondition_failed, client.http_client_failure.get412) - self.assert_raises_with_status(requests.codes.request_entity_too_large, - client.http_client_failure.put413) + self.assert_raises_with_status(requests.codes.request_entity_too_large, client.http_client_failure.put413) - self.assert_raises_with_status(requests.codes.request_uri_too_large, - client.http_client_failure.patch414) + self.assert_raises_with_status(requests.codes.request_uri_too_large, client.http_client_failure.patch414) - self.assert_raises_with_status(requests.codes.unsupported_media, - client.http_client_failure.post415) + self.assert_raises_with_status(requests.codes.unsupported_media, client.http_client_failure.post415) - self.assert_raises_with_status(requests.codes.requested_range_not_satisfiable, - client.http_client_failure.get416) + self.assert_raises_with_status( + requests.codes.requested_range_not_satisfiable, client.http_client_failure.get416 + ) - self.assert_raises_with_status(requests.codes.expectation_failed, - client.http_client_failure.delete417) + self.assert_raises_with_status(requests.codes.expectation_failed, client.http_client_failure.delete417) - self.assert_raises_with_status(429, - client.http_client_failure.head429) + self.assert_raises_with_status(429, client.http_client_failure.head429) def test_redirect_to_300(self, client): self.assert_status(200, client.http_redirects.get300) @@ -371,15 +335,15 @@ def test_redirect_to_307(self, client): self.assert_status(200, client.http_redirects.patch307) self.assert_status(200, client.http_redirects.delete307) - - def test_bad_request_status_assert(self, client): - self.assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.http_failure.get_empty_error) + self.assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", client.http_failure.get_empty_error + ) def test_no_error_model_status_assert(self, client): - self.assert_raises_with_status_and_response_contains(requests.codes.bad_request, "NoErrorModel", - client.http_failure.get_no_model_error) + self.assert_raises_with_status_and_response_contains( + requests.codes.bad_request, "NoErrorModel", client.http_failure.get_no_model_error + ) def test_success_status_codes_200(self, client): client.http_success.head200() @@ -390,7 +354,7 @@ def test_success_status_codes_200(self, client): client.http_success.delete200() # TODO, 4042586: Support options operations in swagger modeler - #assert client.http_success.options200() + # assert client.http_success.options200() def test_success_status_codes_201(self, client): client.http_success.put201() @@ -413,13 +377,13 @@ def test_success_status_codes_404(self, client): client.http_success.head404() def test_empty_no_content(self, client): - self.assert_raises_with_status(requests.codes.bad_request, - client.http_failure.get_no_model_empty) + self.assert_raises_with_status(requests.codes.bad_request, client.http_failure.get_no_model_empty) def test_models(self): from httpinfrastructure.models import Error from httpinfrastructure.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -428,5 +392,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from httpinfrastructure.operations import _multiple_responses_operations_py3 - from httpinfrastructure.operations._multiple_responses_operations import MultipleResponsesOperations as MultipleResponsesOperationsPy2 + from httpinfrastructure.operations._multiple_responses_operations import ( + MultipleResponsesOperations as MultipleResponsesOperationsPy2, + ) + assert MultipleResponsesOperations == MultipleResponsesOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_incorrect_error_response.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_incorrect_error_response.py index f3db0b1f7e2..50274449171 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_incorrect_error_response.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_incorrect_error_response.py @@ -28,16 +28,21 @@ from azure.core.exceptions import HttpResponseError from incorrecterrorresponse import IncorrectReturnedErrorModel + def test_swallow_deserialization_error_for_error_model(): client = IncorrectReturnedErrorModel(base_url="http://localhost:3000") with pytest.raises(HttpResponseError): client.get_incorrect_error_from_server() + def test_operation_groups(): from incorrecterrorresponse.operations import IncorrectReturnedErrorModelOperationsMixin with pytest.raises(ImportError): from incorrecterrorresponse.operations import _incorrect_returned_error_model_operations_py3 - from incorrecterrorresponse.operations._incorrect_returned_error_model_operations import IncorrectReturnedErrorModelOperationsMixin as IncorrectReturnedErrorModelOperationsMixinPy2 - assert IncorrectReturnedErrorModelOperationsMixin == IncorrectReturnedErrorModelOperationsMixinPy2 \ No newline at end of file + from incorrecterrorresponse.operations._incorrect_returned_error_model_operations import ( + IncorrectReturnedErrorModelOperationsMixin as IncorrectReturnedErrorModelOperationsMixinPy2, + ) + + assert IncorrectReturnedErrorModelOperationsMixin == IncorrectReturnedErrorModelOperationsMixinPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_inputs.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_inputs.py index 8ec61856d32..7b9a23d5d92 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_inputs.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_inputs.py @@ -26,39 +26,47 @@ import pytest from bodycomplex import AutoRestComplexTestService from azure.core.pipeline.policies import CustomHookPolicy + try: from urlparse import urlparse # type: ignore except ImportError: from urllib.parse import urlparse + def get_client(callback): return AutoRestComplexTestService(policies=[CustomHookPolicy(raw_request_hook=callback)]) + def test_header_input(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 2 assert pipeline_request.http_request.headers["hello"] == "world!" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: client.basic.get_empty(headers={"hello": "world!"}) assert str(ex.value) == "Passed!" + def test_header_input_override(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 1 assert pipeline_request.http_request.headers["Accept"] == "my/content-type" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: client.basic.get_empty(headers={"Accept": "my/content-type"}) assert str(ex.value) == "Passed!" + def test_header_none_input(): with AutoRestComplexTestService() as client: client.basic.get_empty(headers=None) + def test_header_case_insensitive(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 1 @@ -72,25 +80,30 @@ def get_headers(pipeline_request): client.basic.get_empty(headers={accept_key: "my/content-type"}) assert str(ex.value) == "Passed!" + def test_header_kwarg_and_header(): def get_headers(pipeline_request): assert pipeline_request.http_request.headers["content-type"] == "my/json" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: client.basic.put_valid({}, headers={"content-type": "shouldn't/be-me"}, content_type="my/json") assert str(ex.value) == "Passed!" + def test_query_input(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "foo=bar" raise ValueError("Passed!") + client = get_client(callback=get_query) with pytest.raises(ValueError) as ex: client.basic.get_empty(params={"foo": "bar"}) assert str(ex.value) == "Passed!" + def test_query_input_override(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "api-version=2021-10-01" @@ -103,10 +116,12 @@ def get_query(pipeline_request): assert str(ex.value) == "Passed!" + def test_query_none_input(): with AutoRestComplexTestService() as client: client.basic.get_empty(params=None) + def test_query_case_insensitive(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query.lower() == "foo=bar" @@ -119,6 +134,7 @@ def get_query(pipeline_request): client.basic.get_empty(params={query_key: "bar"}) assert str(ex.value) == "Passed!" + def test_query_kwarg_and_header(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "api-version=2021-10-01" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_integer.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_integer.py index 737372a7525..18601b71a03 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_integer.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_integer.py @@ -40,15 +40,17 @@ import pytest + @pytest.fixture def client(): with AutoRestIntegerTestService(base_url="http://localhost:3000") as client: yield client + class TestInteger(object): def test_max_min_32_bit(self, client): - client.int_operations.put_max32(2147483647) # sys.maxint + client.int_operations.put_max32(2147483647) # sys.maxint client.int_operations.put_min32(-2147483648) def test_max_min_64_bit(self, client): @@ -73,7 +75,7 @@ def test_get_underflow(self, client): def test_unix_time_date(self, client): unix_date = datetime(year=2016, month=4, day=13) client.int_operations.put_unix_time_date(unix_date) - assert unix_date.utctimetuple() == client.int_operations.get_unix_time().utctimetuple() + assert unix_date.utctimetuple() == client.int_operations.get_unix_time().utctimetuple() def test_get_null_and_invalid_unix_time(self, client): assert client.int_operations.get_null_unix_time() is None @@ -85,6 +87,7 @@ def test_models(self): from bodyinteger.models import Error from bodyinteger.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -94,4 +97,5 @@ def test_operation_groups(self): from bodyinteger.operations import _int_operations_operations_py3 from bodyinteger.operations._int_operations_operations import IntOperations as IntOperationsPy2 + assert IntOperations == IntOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_media_types.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_media_types.py index 0d130deb1ac..8506007635f 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_media_types.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_media_types.py @@ -30,6 +30,7 @@ import json import sys + @pytest.fixture def client(): with MediaTypesClient() as client: @@ -48,7 +49,7 @@ def test_json(self, client): assert result == "Nice job with JSON" def test_content_type_with_encoding(self, client): - result = client.content_type_with_encoding(input="hello", content_type='text/plain; charset=UTF-8') + result = client.content_type_with_encoding(input="hello", content_type="text/plain; charset=UTF-8") assert result == "Nice job sending content type with encoding" def test_pdf_no_accept_header(self, client): @@ -59,14 +60,14 @@ def test_json_no_accept_header(self, client): client.analyze_body_no_accept_header(input=json_input) def test_binary_body_two_content_types(self, client): - json_input = json.dumps({"hello":"world"}) + json_input = json.dumps({"hello": "world"}) client.binary_body_with_two_content_types(json_input, content_type="application/json") content = b"hello, world" client.binary_body_with_two_content_types(content, content_type="application/octet-stream") def test_binary_body_three_content_types(self, client): - json_input = json.dumps({"hello":"world"}) + json_input = json.dumps({"hello": "world"}) client.binary_body_with_three_content_types(json_input) content = b"hello, world" @@ -76,7 +77,7 @@ def test_binary_body_three_content_types(self, client): client.binary_body_with_three_content_types(content, content_type="text/plain") def test_body_three_types(self, client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} client.body_three_types(json_input) content = b"hello, world" @@ -86,6 +87,7 @@ def test_models(self): from mediatypes.models import SourcePath from mediatypes.models._models_py3 import SourcePath as SourcePathPy3 + assert SourcePath == SourcePathPy3 def test_operation_groups(self): @@ -94,5 +96,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from mediatypes.operations import _media_types_client_operations_py3 - from mediatypes.operations._media_types_client_operations import MediaTypesClientOperationsMixin as MediaTypesClientOperationsMixinPy2 + from mediatypes.operations._media_types_client_operations import ( + MediaTypesClientOperationsMixin as MediaTypesClientOperationsMixinPy2, + ) + assert MediaTypesClientOperationsMixin == MediaTypesClientOperationsMixinPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_merge_patch_json.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_merge_patch_json.py index b5626f40dd6..f6aab3f6708 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_merge_patch_json.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_merge_patch_json.py @@ -27,10 +27,12 @@ import pytest + @pytest.fixture def client(): with MergePatchJsonClient() as client: yield client + def test_merge_patch_json(client): client.patch_single({"foo": "bar"}) == "Success!" diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_model_flattening.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_model_flattening.py index 4d7908a7c81..75b2a86496c 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_model_flattening.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_model_flattening.py @@ -35,237 +35,231 @@ from os.path import dirname, pardir, join, realpath from modelflattening import AutoRestResourceFlatteningTestService -from modelflattening.models import ( - FlattenedProduct, - ResourceCollection, - SimpleProduct) +from modelflattening.models import FlattenedProduct, ResourceCollection, SimpleProduct import pytest + @pytest.fixture() def client(): with AutoRestResourceFlatteningTestService(base_url="http://localhost:3000") as client: yield client + class TestModelFlatteningTests(object): def test_flattening_array(self, client): - #Array + # Array result = client.get_array() - assert 3 == len(result) + assert 3 == len(result) # Resource 1 - assert "1" == result[0].id - assert "OK" == result[0].provisioning_state_values - assert "Product1" == result[0].p_name - assert "Flat" == result[0].type_properties_type - assert "Building 44" == result[0].location - assert "Resource1" == result[0].name - assert "Succeeded" == result[0].provisioning_state - assert "Microsoft.Web/sites" == result[0].type - assert "value1" == result[0].tags["tag1"] - assert "value3" == result[0].tags["tag2"] + assert "1" == result[0].id + assert "OK" == result[0].provisioning_state_values + assert "Product1" == result[0].p_name + assert "Flat" == result[0].type_properties_type + assert "Building 44" == result[0].location + assert "Resource1" == result[0].name + assert "Succeeded" == result[0].provisioning_state + assert "Microsoft.Web/sites" == result[0].type + assert "value1" == result[0].tags["tag1"] + assert "value3" == result[0].tags["tag2"] # Resource 2 - assert "2" == result[1].id - assert "Resource2" == result[1].name - assert "Building 44" == result[1].location + assert "2" == result[1].id + assert "Resource2" == result[1].name + assert "Building 44" == result[1].location # Resource 3 - assert "3" == result[2].id - assert "Resource3" == result[2].name + assert "3" == result[2].id + assert "Resource3" == result[2].name resourceArray = [ - { - 'location': "West US", - 'tags': {"tag1":"value1", "tag2":"value3"}}, - { - 'location': "Building 44"}] + {"location": "West US", "tags": {"tag1": "value1", "tag2": "value3"}}, + {"location": "Building 44"}, + ] client.put_array(resourceArray) def test_flattening_dictionary(self, client): - #Dictionary + # Dictionary resultDictionary = client.get_dictionary() - assert 3 == len(resultDictionary) + assert 3 == len(resultDictionary) # Resource 1 - assert "1" == resultDictionary["Product1"].id - assert "OK" == resultDictionary["Product1"].provisioning_state_values - assert "Product1" == resultDictionary["Product1"].p_name - assert "Flat" == resultDictionary["Product1"].type_properties_type - assert "Building 44" == resultDictionary["Product1"].location - assert "Resource1" == resultDictionary["Product1"].name - assert "Succeeded" == resultDictionary["Product1"].provisioning_state - assert "Microsoft.Web/sites" == resultDictionary["Product1"].type - assert "value1" == resultDictionary["Product1"].tags["tag1"] - assert "value3" == resultDictionary["Product1"].tags["tag2"] + assert "1" == resultDictionary["Product1"].id + assert "OK" == resultDictionary["Product1"].provisioning_state_values + assert "Product1" == resultDictionary["Product1"].p_name + assert "Flat" == resultDictionary["Product1"].type_properties_type + assert "Building 44" == resultDictionary["Product1"].location + assert "Resource1" == resultDictionary["Product1"].name + assert "Succeeded" == resultDictionary["Product1"].provisioning_state + assert "Microsoft.Web/sites" == resultDictionary["Product1"].type + assert "value1" == resultDictionary["Product1"].tags["tag1"] + assert "value3" == resultDictionary["Product1"].tags["tag2"] # Resource 2 - assert "2" == resultDictionary["Product2"].id - assert "Resource2" == resultDictionary["Product2"].name - assert "Building 44" == resultDictionary["Product2"].location + assert "2" == resultDictionary["Product2"].id + assert "Resource2" == resultDictionary["Product2"].name + assert "Building 44" == resultDictionary["Product2"].location # Resource 3 - assert "3" == resultDictionary["Product3"].id - assert "Resource3" == resultDictionary["Product3"].name + assert "3" == resultDictionary["Product3"].id + assert "Resource3" == resultDictionary["Product3"].name resourceDictionary = { - "Resource1": { - 'location': "West US", - 'tags': {"tag1":"value1", "tag2":"value3"}, - 'p_name': "Product1", - 'type_properties_type': "Flat"}, - "Resource2": { - 'location': "Building 44", - 'p_name': "Product2", - 'type_properties_type': "Flat"}} + "Resource1": { + "location": "West US", + "tags": {"tag1": "value1", "tag2": "value3"}, + "p_name": "Product1", + "type_properties_type": "Flat", + }, + "Resource2": {"location": "Building 44", "p_name": "Product2", "type_properties_type": "Flat"}, + } client.put_dictionary(resourceDictionary) def test_flattening_complex_object(self, client): - #ResourceCollection + # ResourceCollection resultResource = client.get_resource_collection() - #dictionaryofresources - assert 3 == len(resultResource.dictionaryofresources) + # dictionaryofresources + assert 3 == len(resultResource.dictionaryofresources) # Resource 1 - assert "1" == resultResource.dictionaryofresources["Product1"].id - assert "OK" == resultResource.dictionaryofresources["Product1"].provisioning_state_values - assert "Product1" == resultResource.dictionaryofresources["Product1"].p_name - assert "Flat" == resultResource.dictionaryofresources["Product1"].type_properties_type - assert "Building 44" == resultResource.dictionaryofresources["Product1"].location - assert "Resource1" == resultResource.dictionaryofresources["Product1"].name - assert "Succeeded" == resultResource.dictionaryofresources["Product1"].provisioning_state - assert "Microsoft.Web/sites" == resultResource.dictionaryofresources["Product1"].type - assert "value1" == resultResource.dictionaryofresources["Product1"].tags["tag1"] - assert "value3" == resultResource.dictionaryofresources["Product1"].tags["tag2"] + assert "1" == resultResource.dictionaryofresources["Product1"].id + assert "OK" == resultResource.dictionaryofresources["Product1"].provisioning_state_values + assert "Product1" == resultResource.dictionaryofresources["Product1"].p_name + assert "Flat" == resultResource.dictionaryofresources["Product1"].type_properties_type + assert "Building 44" == resultResource.dictionaryofresources["Product1"].location + assert "Resource1" == resultResource.dictionaryofresources["Product1"].name + assert "Succeeded" == resultResource.dictionaryofresources["Product1"].provisioning_state + assert "Microsoft.Web/sites" == resultResource.dictionaryofresources["Product1"].type + assert "value1" == resultResource.dictionaryofresources["Product1"].tags["tag1"] + assert "value3" == resultResource.dictionaryofresources["Product1"].tags["tag2"] # Resource 2 - assert "2" == resultResource.dictionaryofresources["Product2"].id - assert "Resource2" == resultResource.dictionaryofresources["Product2"].name - assert "Building 44" == resultResource.dictionaryofresources["Product2"].location + assert "2" == resultResource.dictionaryofresources["Product2"].id + assert "Resource2" == resultResource.dictionaryofresources["Product2"].name + assert "Building 44" == resultResource.dictionaryofresources["Product2"].location # Resource 3 - assert "3" == resultResource.dictionaryofresources["Product3"].id - assert "Resource3" == resultResource.dictionaryofresources["Product3"].name + assert "3" == resultResource.dictionaryofresources["Product3"].id + assert "Resource3" == resultResource.dictionaryofresources["Product3"].name - #arrayofresources - assert 3 == len(resultResource.arrayofresources) + # arrayofresources + assert 3 == len(resultResource.arrayofresources) # Resource 1 - assert "4" == resultResource.arrayofresources[0].id - assert "OK" == resultResource.arrayofresources[0].provisioning_state_values - assert "Product4" == resultResource.arrayofresources[0].p_name - assert "Flat" == resultResource.arrayofresources[0].type_properties_type - assert "Building 44" == resultResource.arrayofresources[0].location - assert "Resource4" == resultResource.arrayofresources[0].name - assert "Succeeded" == resultResource.arrayofresources[0].provisioning_state - assert "Microsoft.Web/sites" == resultResource.arrayofresources[0].type - assert "value1" == resultResource.arrayofresources[0].tags["tag1"] - assert "value3" == resultResource.arrayofresources[0].tags["tag2"] + assert "4" == resultResource.arrayofresources[0].id + assert "OK" == resultResource.arrayofresources[0].provisioning_state_values + assert "Product4" == resultResource.arrayofresources[0].p_name + assert "Flat" == resultResource.arrayofresources[0].type_properties_type + assert "Building 44" == resultResource.arrayofresources[0].location + assert "Resource4" == resultResource.arrayofresources[0].name + assert "Succeeded" == resultResource.arrayofresources[0].provisioning_state + assert "Microsoft.Web/sites" == resultResource.arrayofresources[0].type + assert "value1" == resultResource.arrayofresources[0].tags["tag1"] + assert "value3" == resultResource.arrayofresources[0].tags["tag2"] # Resource 2 - assert "5" == resultResource.arrayofresources[1].id - assert "Resource5" == resultResource.arrayofresources[1].name - assert "Building 44" == resultResource.arrayofresources[1].location + assert "5" == resultResource.arrayofresources[1].id + assert "Resource5" == resultResource.arrayofresources[1].name + assert "Building 44" == resultResource.arrayofresources[1].location # Resource 3 - assert "6" == resultResource.arrayofresources[2].id - assert "Resource6" == resultResource.arrayofresources[2].name + assert "6" == resultResource.arrayofresources[2].id + assert "Resource6" == resultResource.arrayofresources[2].name - #productresource - assert "7" == resultResource.productresource.id - assert "Resource7" == resultResource.productresource.name + # productresource + assert "7" == resultResource.productresource.id + assert "Resource7" == resultResource.productresource.name resourceDictionary = { - "Resource1": FlattenedProduct( - location = "West US", - tags = {"tag1":"value1", "tag2":"value3"}, - p_name = "Product1", - type_properties_type = "Flat"), - "Resource2": FlattenedProduct( - location = "Building 44", - p_name = "Product2", - type_properties_type = "Flat")} + "Resource1": FlattenedProduct( + location="West US", + tags={"tag1": "value1", "tag2": "value3"}, + p_name="Product1", + type_properties_type="Flat", + ), + "Resource2": FlattenedProduct(location="Building 44", p_name="Product2", type_properties_type="Flat"), + } resourceComplexObject = ResourceCollection( - dictionaryofresources = resourceDictionary, - arrayofresources = [ - FlattenedProduct( - location = "West US", - tags = {"tag1":"value1", "tag2":"value3"}, - p_name = "Product1", - type_properties_type = "Flat"), - FlattenedProduct( - location = "East US", - p_name = "Product2", - type_properties_type = "Flat")], - productresource = FlattenedProduct( - location = "India", - p_name = "Azure", - type_properties_type = "Flat")) + dictionaryofresources=resourceDictionary, + arrayofresources=[ + FlattenedProduct( + location="West US", + tags={"tag1": "value1", "tag2": "value3"}, + p_name="Product1", + type_properties_type="Flat", + ), + FlattenedProduct(location="East US", p_name="Product2", type_properties_type="Flat"), + ], + productresource=FlattenedProduct(location="India", p_name="Azure", type_properties_type="Flat"), + ) client.put_resource_collection(resourceComplexObject) def test_model_flattening_simple(self, client): simple_product = SimpleProduct( - product_id = "123", - description = "product description", - max_product_display_name = "max name", + product_id="123", + description="product description", + max_product_display_name="max name", capacity="Large", - odata_value = "http://foo", - generic_value = "https://generic" + odata_value="http://foo", + generic_value="https://generic", ) - simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. + simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. result = client.put_simple_product(simple_product) - result.additional_properties = {} # Not the purpose of this test. This enables the ==. - assert result == simple_product + result.additional_properties = {} # Not the purpose of this test. This enables the ==. + assert result == simple_product def test_model_flattening_with_parameter_flattening(self, client): simple_product = SimpleProduct( - product_id = "123", - description = "product description", - max_product_display_name = "max name", + product_id="123", + description="product description", + max_product_display_name="max name", capacity="Large", - odata_value = "http://foo" + odata_value="http://foo", ) - simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. + simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. result = client.post_flattened_simple_product( - "123", # product_id - "product description", # description - "max name", # max_product_display_name + "123", # product_id + "product description", # description + "max name", # max_product_display_name "Large", # capacity - None, # generic_value - "http://foo", # odata_value + None, # generic_value + "http://foo", # odata_value ) - result.additional_properties = {} # Not the purpose of this test. This enables the ==. - assert result == simple_product + result.additional_properties = {} # Not the purpose of this test. This enables the ==. + assert result == simple_product def test_model_flattening_with_grouping(self, client): from modelflattening.models import FlattenParameterGroup simple_product = SimpleProduct( - product_id = "123", - description = "product description", - max_product_display_name = "max name", + product_id="123", + description="product description", + max_product_display_name="max name", capacity="Large", - odata_value = "http://foo" + odata_value="http://foo", ) - simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. + simple_product.additional_properties = {} # Not the purpose of this test. This enables the ==. group = FlattenParameterGroup( - product_id = "123", - description = "product description", + product_id="123", + description="product description", max_product_display_name="max name", capacity="Large", odata_value="http://foo", - name="groupproduct") + name="groupproduct", + ) result = client.put_simple_product_with_grouping(group) - result.additional_properties = {} # Not the purpose of this test. This enables the ==. - assert result == simple_product + result.additional_properties = {} # Not the purpose of this test. This enables the ==. + assert result == simple_product def test_models(self): from modelflattening.models import Error from modelflattening.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -274,5 +268,11 @@ def test_operation_groups(self): with pytest.raises(ImportError): from modelflattening.operations import _auto_rest_resource_flattening_test_service_operations_py3 - from modelflattening.operations._auto_rest_resource_flattening_test_service_operations import AutoRestResourceFlatteningTestServiceOperationsMixin as AutoRestResourceFlatteningTestServiceOperationsMixinPy2 - assert AutoRestResourceFlatteningTestServiceOperationsMixin == AutoRestResourceFlatteningTestServiceOperationsMixinPy2 + from modelflattening.operations._auto_rest_resource_flattening_test_service_operations import ( + AutoRestResourceFlatteningTestServiceOperationsMixin as AutoRestResourceFlatteningTestServiceOperationsMixinPy2, + ) + + assert ( + AutoRestResourceFlatteningTestServiceOperationsMixin + == AutoRestResourceFlatteningTestServiceOperationsMixinPy2 + ) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_multiple_inheritance.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_multiple_inheritance.py index da8f176868e..c1ef4dc8106 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_multiple_inheritance.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_multiple_inheritance.py @@ -31,11 +31,13 @@ import pytest import sys + @pytest.fixture def client(): with MultipleInheritanceServiceClient(base_url="http://localhost:3000") as client: yield client + class TestMultipleInheritance(object): def test_get_pet(self, client): @@ -67,7 +69,9 @@ def test_put_cat(self, client): assert result == "Cat was correct!" def test_get_kitten(self, client): - assert Kitten(name="Gatito", likes_milk=True, meows=True, hisses=True, eats_mice_yet=False) == client.get_kitten() + assert ( + Kitten(name="Gatito", likes_milk=True, meows=True, hisses=True, eats_mice_yet=False) == client.get_kitten() + ) def test_put_kitten(self, client): result = client.put_kitten(Kitten(name="Kitty", likes_milk=False, meows=True, hisses=False, eats_mice_yet=True)) @@ -77,6 +81,7 @@ def test_models(self): from multipleinheritance.models import Error from multipleinheritance.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -85,5 +90,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from multipleinheritance.operations import _multiple_inheritance_service_client_operations_py3 - from multipleinheritance.operations._multiple_inheritance_service_client_operations import MultipleInheritanceServiceClientOperationsMixin as MultipleInheritanceServiceClientOperationsMixinPy2 + from multipleinheritance.operations._multiple_inheritance_service_client_operations import ( + MultipleInheritanceServiceClientOperationsMixin as MultipleInheritanceServiceClientOperationsMixinPy2, + ) + assert MultipleInheritanceServiceClientOperationsMixin == MultipleInheritanceServiceClientOperationsMixinPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_no_operations.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_no_operations.py index 64478b99bdc..4bd461b8395 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_no_operations.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_no_operations.py @@ -27,14 +27,15 @@ import sys import pytest + class TestNoOperations: def test_models(self): from nooperations.models import Error from nooperations.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): with pytest.raises(ImportError): from nooperations import operations - diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_non_string_enums.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_non_string_enums.py index 6e6740abc1f..4edbfed76e8 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_non_string_enums.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_non_string_enums.py @@ -30,6 +30,7 @@ import pytest import json + @pytest.fixture def client(): with NonStringEnumsClient() as client: @@ -65,4 +66,5 @@ def test_operation_groups(self): from nonstringenums.operations import _float_operations_py3 from nonstringenums.operations._float_operations import FloatOperations as FloatOperationsPy2 + assert FloatOperations == FloatOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_number.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_number.py index 8867bdb7ade..349781d97aa 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_number.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_number.py @@ -42,52 +42,54 @@ import pytest + @pytest.fixture def client(): with AutoRestNumberTestService(base_url="http://localhost:3000") as client: yield client + class TestNumber(object): def test_big_float(self, client): - client.number.put_big_float(3.402823e+20) - assert client.number.get_big_float() == 3.402823e+20 + client.number.put_big_float(3.402823e20) + assert client.number.get_big_float() == 3.402823e20 def test_small_float(self, client): client.number.put_small_float(3.402823e-20) - assert client.number.get_small_float() == 3.402823e-20 + assert client.number.get_small_float() == 3.402823e-20 def test_big_double(self, client): - client.number.put_big_double(2.5976931e+101) - assert client.number.get_big_double() == 2.5976931e+101 + client.number.put_big_double(2.5976931e101) + assert client.number.get_big_double() == 2.5976931e101 def test_small_double(self, client): client.number.put_small_double(2.5976931e-101) - assert client.number.get_small_double() == 2.5976931e-101 + assert client.number.get_small_double() == 2.5976931e-101 def test_big_double_negative_decimal(self, client): client.number.put_big_double_negative_decimal() - assert client.number.get_big_double_negative_decimal() == -99999999.99 + assert client.number.get_big_double_negative_decimal() == -99999999.99 def test_big_double_positive_decimal(self, client): client.number.put_big_double_positive_decimal() - assert client.number.get_big_double_positive_decimal() == 99999999.99 + assert client.number.get_big_double_positive_decimal() == 99999999.99 def test_big_decimal(self, client): - client.number.put_big_decimal(Decimal(2.5976931e+101)) - assert client.number.get_big_decimal() == 2.5976931e+101 + client.number.put_big_decimal(Decimal(2.5976931e101)) + assert client.number.get_big_decimal() == 2.5976931e101 def test_small_decimal(self, client): client.number.put_small_decimal(Decimal(2.5976931e-101)) - assert client.number.get_small_decimal() == 2.5976931e-101 + assert client.number.get_small_decimal() == 2.5976931e-101 def test_get_big_decimal_negative_decimal(self, client): client.number.put_big_decimal_positive_decimal() - assert client.number.get_big_decimal_negative_decimal() == -99999999.99 + assert client.number.get_big_decimal_negative_decimal() == -99999999.99 def test_get_big_decimal_positive_decimal(self, client): client.number.put_big_decimal_negative_decimal() - assert client.number.get_big_decimal_positive_decimal() == 99999999.99 + assert client.number.get_big_decimal_positive_decimal() == 99999999.99 def test_get_null(self, client): client.number.get_null() @@ -108,6 +110,7 @@ def test_models(self): from bodynumber.models import Error from bodynumber.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -117,4 +120,5 @@ def test_operation_groups(self): from bodynumber.operations import _number_operations_py3 from bodynumber.operations._number_operations import NumberOperations as NumberOperationsPy2 + assert NumberOperations == NumberOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_object_type.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_object_type.py index decdee10735..d8181f59317 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_object_type.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_object_type.py @@ -29,11 +29,13 @@ import pytest + @pytest.fixture def client(): with ObjectTypeClient(base_url="http://localhost:3000") as client: yield client + class TestObjectType(object): def test_get_object(self, client): @@ -55,5 +57,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from objecttype.operations import _object_type_client_operations_py3 - from objecttype.operations._object_type_client_operations import ObjectTypeClientOperationsMixin as ObjectTypeClientOperationsMixinPy2 - assert ObjectTypeClientOperationsMixin == ObjectTypeClientOperationsMixinPy2 \ No newline at end of file + from objecttype.operations._object_type_client_operations import ( + ObjectTypeClientOperationsMixin as ObjectTypeClientOperationsMixinPy2, + ) + + assert ObjectTypeClientOperationsMixin == ObjectTypeClientOperationsMixinPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_packagemode.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_packagemode.py index e41dda7ce6a..58c3a436745 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_packagemode.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_packagemode.py @@ -26,25 +26,32 @@ import pytest from packagemode import AnythingClient + @pytest.fixture def client(): with AnythingClient(base_url="http://localhost:3000") as client: yield client + def test_get_string(client): - assert client.get_string() == 'anything' + assert client.get_string() == "anything" + def test_put_string(client): client.put_string(input="anything") + def test_get_object(client): assert client.get_object() == {"message": "An object was successfully returned"} + def test_put_object(client): - client.put_object({'foo': 'bar'}) + client.put_object({"foo": "bar"}) + def test_get_array(client): - assert client.get_array() == ['foo', 'bar'] + assert client.get_array() == ["foo", "bar"] + def test_put_array(client): - client.put_array(['foo', 'bar']) + client.put_array(["foo", "bar"]) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_parameterized_endpoint.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_parameterized_endpoint.py index 2f4be68140d..12dd0af4afe 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_parameterized_endpoint.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_parameterized_endpoint.py @@ -26,6 +26,7 @@ import pytest from parameterizedendpoint import ParmaterizedEndpointClient + @pytest.fixture def client(): with ParmaterizedEndpointClient(endpoint="http://localhost:3000") as client: diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_required_optional.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_required_optional.py index f981224843c..efe0fdc1dc7 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_required_optional.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_required_optional.py @@ -40,26 +40,27 @@ import pytest + @pytest.fixture def client_required(): with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - base_url="http://localhost:3000") as client: + "required_path", "required_query", base_url="http://localhost:3000" + ) as client: client._config.required_global_path = "required_path" client._config.required_global_query = "required_query" yield client + @pytest.fixture def client(): with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - base_url="http://localhost:3000") as client: + "required_path", "required_query", base_url="http://localhost:3000" + ) as client: client._config.required_global_path = None client._config.required_global_query = None yield client + class TestRequiredOptional(object): # These clients have a required global path and query @@ -131,6 +132,7 @@ def test_models(self): from requiredoptional.models import Error from requiredoptional.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_explict_put_optional_binary_body(self, client): @@ -138,7 +140,7 @@ def test_explict_put_optional_binary_body(self, client): def test_explict_put_required_binary_body(self, client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: client.explicit.put_required_binary_body(stream_data) @@ -152,4 +154,5 @@ def test_operation_groups(self): from requiredoptional.operations import _explicit_operations_py3 from requiredoptional.operations._explicit_operations import ExplicitOperations as ExplicitOperationsPy2 + assert ExplicitOperations == ExplicitOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_reserved_words.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_reserved_words.py index 96cdae36897..3774520f8a6 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_reserved_words.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_reserved_words.py @@ -26,28 +26,36 @@ import pytest from reservedwords import ReservedWordsClient, models + @pytest.fixture def client(): with ReservedWordsClient() as client: yield client + def test_operation_group_import(client): client.import_operations.operation_one(parameter1="foo") + def test_operation_with_content_param(client): client.operation_with_content_param(b"hello, world") + def test_operation_with_json_param(client): client.operation_with_json_param({"hello": "world"}) + def test_operation_with_data_param(client): client.operation_with_data_param(data="hello", world="world") + def test_operation_with_files_param(client): client.operation_with_files_param(file_name="my.txt", files=b"bytes") + def test_operation_with_url(client): client.operation_with_url("foo", header_parameters="x-ms-header", query_parameters=["one", "two"]) + def test_operation_with_enum(client): client.reserved_enum(models.MyEnum.IMPORT_ENUM) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_security.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_security.py index 7a4a9cbf547..68a81f54ae3 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_security.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_security.py @@ -32,24 +32,27 @@ from azure.core.pipeline.policies import AzureKeyCredentialPolicy from azure.core.pipeline.policies import BearerTokenCredentialPolicy + def test_security_aad_swagger(credential): client = AutorestSecurityAad(credential=credential) assert isinstance(client._config.authentication_policy, BearerTokenCredentialPolicy) client.head(enforce_https=False) + def test_security_key_swagger(): # the key value shall keep same with https://github.com/Azure/autorest.testserver/tree/main/src/test-routes/security.ts - client = AutorestSecurityKey(credential=AzureKeyCredential('123456789')) + client = AutorestSecurityKey(credential=AzureKeyCredential("123456789")) assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) client.head() + def test_security_aad_swagger_cred_flag(): - client = SecurityAadSwaggerCredentialFlag(credential=AzureKeyCredential('123456789')) + client = SecurityAadSwaggerCredentialFlag(credential=AzureKeyCredential("123456789")) assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) + def test_security_key_swagger_cred_flag(credential): client = SecurityKeySwaggerCredentialFlag( - credential=credential, - credential_scopes=['https://fake.azure.com/.default'] + credential=credential, credential_scopes=["https://fake.azure.com/.default"] ) assert isinstance(client._config.authentication_policy, BearerTokenCredentialPolicy) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_send_request.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_send_request.py index 2275bb2af63..5b4e79e5b88 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_send_request.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_send_request.py @@ -42,18 +42,18 @@ def test_send_request_with_body_get_model_deserialize(self): client = AutoRestComplexTestService(base_url="http://localhost:3000") - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = client._send_request(request) deserialized = Siamese.deserialize(response) - assert 2 == deserialized.id - assert "Siameeee" == deserialized.name - assert -1 == deserialized.hates[1].id + assert 2 == deserialized.id + assert "Siameeee" == deserialized.name + assert -1 == deserialized.hates[1].id assert "Tomato" == deserialized.hates[1].name def test_send_request_with_body_get_direct_json(self): @@ -62,20 +62,20 @@ def test_send_request_with_body_get_direct_json(self): client = AutoRestComplexTestService(base_url="http://localhost:3000") - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = client._send_request(request, stream=True) - data = b''.join([chunk for chunk in response.stream_download(None)]).decode('utf-8') + data = b"".join([chunk for chunk in response.stream_download(None)]).decode("utf-8") json_response = json.loads(data) - assert 2 == json_response['id'] - assert "Siameeee" == json_response['name'] - assert - 1 == json_response['hates'][1]['id'] - assert "Tomato" == json_response['hates'][1]['name'] + assert 2 == json_response["id"] + assert "Siameeee" == json_response["name"] + assert -1 == json_response["hates"][1]["id"] + assert "Tomato" == json_response["hates"][1]["name"] def test_send_request_with_body_put_json_dumps(self): from bodycomplex import AutoRestComplexTestService @@ -86,27 +86,14 @@ def test_send_request_with_body_put_json_dumps(self): "id": 2, "name": "Siameeee", "color": "green", - "hates": - [ - { - "id": 1, - "name": "Potato", - "food": "tomato" - }, - { - "id": -1, - "name": "Tomato", - "food": "french fries" - } - ], - "breed": "persian" + "hates": [ + {"id": 1, "name": "Potato", "food": "tomato"}, + {"id": -1, "name": "Tomato", "food": "french fries"}, + ], + "breed": "persian", } - request = HttpRequest("PUT", "/complex/inheritance/valid", - headers={ - 'Content-Type': 'application/json' - } - ) + request = HttpRequest("PUT", "/complex/inheritance/valid", headers={"Content-Type": "application/json"}) request.set_json_body(siamese_body) response = client._send_request(request) @@ -122,26 +109,11 @@ def test_send_request_with_body_serialize(self): id=2, name="Siameeee", color="green", - hates=[ - Dog( - id=1, - name="Potato", - food="tomato" - ), - Dog( - id=-1, - name="Tomato", - food="french fries" - ) - ], - breed="persian" + hates=[Dog(id=1, name="Potato", food="tomato"), Dog(id=-1, name="Tomato", food="french fries")], + breed="persian", ) - request = HttpRequest("PUT", "/complex/inheritance/valid", - headers={ - 'Content-Type': 'application/json' - } - ) + request = HttpRequest("PUT", "/complex/inheritance/valid", headers={"Content-Type": "application/json"}) request.set_json_body(siamese.serialize()) response = client._send_request(request) assert response.status_code == 200 @@ -153,10 +125,10 @@ def test_send_request_get_stream(self): file_length = 0 with io.BytesIO() as file_handle: - request = HttpRequest("GET", "/files/stream/nonempty", - headers={ - 'Accept': 'image/png, application/json' - }, + request = HttpRequest( + "GET", + "/files/stream/nonempty", + headers={"Accept": "image/png, application/json"}, ) response = client._send_request(request, stream=True) @@ -170,16 +142,27 @@ def test_send_request_get_stream(self): for data in stream: assert 0 < len(data) <= stream.block_size file_length += len(data) - print("Downloading... {}%".format(int(file_length*100/total))) + print("Downloading... {}%".format(int(file_length * 100 / total))) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) + join( + cwd, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) - with open(sample_file, 'rb') as data: + with open(sample_file, "rb") as data: sample_data = hash(data.read()) assert sample_data == hash(file_handle.getvalue()) @@ -191,12 +174,12 @@ def test_send_request_put_stream(self): ) test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: - request = HttpRequest("PUT", '/formdata/stream/uploadfile', - headers={ - 'Content-Type': 'application/octet-stream' - }, + request = HttpRequest( + "PUT", + "/formdata/stream/uploadfile", + headers={"Content-Type": "application/octet-stream"}, data=stream_data, ) response = client._send_request(request, stream=True) @@ -208,16 +191,16 @@ def test_send_request_full_url(self): client = AutoRestComplexTestService(base_url="http://fakeUrl") - request = HttpRequest("GET", "http://localhost:3000/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "http://localhost:3000/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = client._send_request(request) deserialized = Siamese.deserialize(response) - assert 2 == deserialized.id - assert "Siameeee" == deserialized.name - assert -1 == deserialized.hates[1].id - assert "Tomato" == deserialized.hates[1].name + assert 2 == deserialized.id + assert "Siameeee" == deserialized.name + assert -1 == deserialized.hates[1].id + assert "Tomato" == deserialized.hates[1].name diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_string_tests.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_string_tests.py index 57088a8f16c..d4efedbcac5 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_string_tests.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_string_tests.py @@ -41,11 +41,13 @@ from bodystring.models import Colors import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATService(base_url="http://localhost:3000") as client: yield client + class TestString(object): def test_null(self, client): @@ -53,7 +55,7 @@ def test_null(self, client): client.string.put_null() def test_empty(self, client): - assert "" == client.string.get_empty() + assert "" == client.string.get_empty() # changing this behavior because of this pr being merged: https://github.com/Azure/autorest.testserver/pull/145/files client.string.put_empty() @@ -73,7 +75,8 @@ def test_mbcs(self, client): "\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" "\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" "\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") except AttributeError: test_str = ( @@ -90,34 +93,35 @@ def test_mbcs(self, client): b"\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" b"\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" b"\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") assert test_str == client.string.get_mbcs() client.string.put_mbcs() def test_whitespace(self, client): test_str = " Now is the time for all good men to come to the aid of their country " - assert test_str == client.string.get_whitespace() + assert test_str == client.string.get_whitespace() client.string.put_whitespace() def test_get_not_provided(self, client): assert client.string.get_not_provided() is None def test_enum_not_expandable(self, client): - assert Colors.RED_COLOR == client.enum.get_not_expandable() - client.enum.put_not_expandable('red color') + assert Colors.RED_COLOR == client.enum.get_not_expandable() + client.enum.put_not_expandable("red color") client.enum.put_not_expandable(Colors.RED_COLOR) # Autorest v3 is switching behavior here. Old Autorest would have thrown a serialization error, # but now we allow the user to pass strings as enums, so the raised exception is different. with pytest.raises(HttpResponseError): - client.enum.put_not_expandable('not a colour') + client.enum.put_not_expandable("not a colour") def test_get_base64_encdoded(self, client): - assert client.string.get_base64_encoded() == 'a string that gets encoded with base64'.encode() + assert client.string.get_base64_encoded() == "a string that gets encoded with base64".encode() def test_base64_url_encoded(self, client): - assert client.string.get_base64_url_encoded() == 'a string that gets encoded with base64url'.encode() - client.string.put_base64_url_encoded('a string that gets encoded with base64url'.encode()) + assert client.string.get_base64_url_encoded() == "a string that gets encoded with base64url".encode() + client.string.put_base64_url_encoded("a string that gets encoded with base64url".encode()) def test_get_null_base64_url_encoded(self, client): assert client.string.get_null_base64_url_encoded() is None @@ -126,11 +130,11 @@ def test_enum_referenced(self, client): client.enum.put_referenced(Colors.RED_COLOR) client.enum.put_referenced("red color") - assert client.enum.get_referenced() == Colors.RED_COLOR + assert client.enum.get_referenced() == Colors.RED_COLOR def test_enum_referenced_constant(self, client): client.enum.put_referenced_constant() - assert client.enum.get_referenced_constant().color_constant == Colors.GREEN_COLOR.value + assert client.enum.get_referenced_constant().color_constant == Colors.GREEN_COLOR.value def test_patch_file(self): from bodystring.models import PatchAddedModel @@ -143,6 +147,7 @@ def test_models(self): from bodystring.models import Error from bodystring.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -152,4 +157,5 @@ def test_operation_groups(self): from bodystring.operations import _enum_operations_py3 from bodystring.operations._enum_operations import EnumOperations as EnumOperationsPy2 + assert EnumOperations == EnumOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_time.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_time.py index 1d3174a682b..493e91865d4 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_time.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_time.py @@ -31,11 +31,13 @@ import pytest import sys + @pytest.fixture def client(): with AutoRestTimeTestService(base_url="http://localhost:3000") as client: yield client + class TestTime(object): def test_get(self, client): @@ -49,6 +51,7 @@ def test_models(self): from bodytime.models import Error from bodytime.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -58,4 +61,5 @@ def test_operation_groups(self): from bodytime.operations import _time_operations_py3 from bodytime.operations._time_operations import TimeOperations as TimeOperationsPy2 + assert TimeOperations == TimeOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_tracing.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_tracing.py index 88ba339b07a..47f39bf5867 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_tracing.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_tracing.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -37,6 +36,7 @@ def has_tracing_decorator(function): source = inspect.getsource(function) return "def wrapper_use_tracer" in source or "@distributed_trace" in source + def test_url(): - with AutoRestUrlTestService('', base_url="dummy url") as client: - assert has_tracing_decorator(client.paths.get_boolean_false) \ No newline at end of file + with AutoRestUrlTestService("", base_url="dummy url") as client: + assert has_tracing_decorator(client.paths.get_boolean_false) diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_url.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_url.py index bcf0b030569..84306c535d2 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_url.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_url.py @@ -41,20 +41,24 @@ import pytest + @pytest.fixture def client(): - with AutoRestUrlTestService('', base_url="http://localhost:3000") as client: + with AutoRestUrlTestService("", base_url="http://localhost:3000") as client: yield client + @pytest.fixture def multi_client(): with AutoRestUrlMutliCollectionFormatTestService("http://localhost:3000") as client: yield client + @pytest.fixture def test_array_query(): return ["ArrayQuery1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + class TestUrl(object): def test_byte_empty_and_null(self, client): client.paths.byte_empty() @@ -63,7 +67,7 @@ def test_byte_empty_and_null(self, client): client.paths.byte_null(None) def test_byte_multi_byte(self, client): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") client.paths.byte_multi_byte(u_bytes) def test_date_null(self, client): @@ -134,7 +138,7 @@ def test_base64_url(self, client): def test_queries_byte(self, client): client.queries.byte_empty() - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") client.queries.byte_multi_byte(u_bytes) client.queries.byte_null() @@ -199,7 +203,7 @@ def test_array_string_multi(self, multi_client, test_array_query): multi_client.queries.array_string_multi_valid(test_array_query) def test_array_string_no_collection_format(self, client): - client.queries.array_string_no_collection_format_empty(['hello', 'nihao', 'bonjour']) + client.queries.array_string_no_collection_format_empty(["hello", "nihao", "bonjour"]) def test_get_all_with_values(self, client): client._config.global_string_path = "globalStringPath" @@ -243,6 +247,7 @@ def test_models(self): from url.models import Error from url.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -256,7 +261,9 @@ def test_operation_groups(self): from urlmulticollectionformat.operations import _queries_operations_py3 from url.operations._queries_operations import QueriesOperations as QueriesOperationsPy2 + assert QueriesOperations == QueriesOperationsPy2 from urlmulticollectionformat.operations._queries_operations import QueriesOperations as QueriesOperationsPy2 + assert MultiCollectionFormatQueriesOperations == QueriesOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_urlencoded.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_urlencoded.py index e1cd65efe35..47a72b9610d 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_urlencoded.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_urlencoded.py @@ -28,11 +28,13 @@ from bodyformurlencodeddata import BodyFormsDataURLEncoded from bodyformurlencodeddata.models import PetFood, PetType + @pytest.fixture def client(): with BodyFormsDataURLEncoded() as client: yield client + def test_update_pet_with_form(client): client.formdataurlencoded.update_pet_with_form( pet_id=1, @@ -42,5 +44,6 @@ def test_update_pet_with_form(client): name="Fido", ) + def test_partial_constant_body(client): client.formdataurlencoded.partial_constant_body(access_token="foo", service="bar") diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_validation.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_validation.py index aacf665b52d..2686f6a4414 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_validation.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_validation.py @@ -37,31 +37,31 @@ from msrest.exceptions import ValidationError from validation import AutoRestValidationTest -from validation.models import ( - Product, - ConstantProduct, - ChildProduct) +from validation.models import Product, ConstantProduct, ChildProduct import pytest + @pytest.fixture def client(): with AutoRestValidationTest("abc123", base_url="http://localhost:3000") as client: client.api_version = "12-34-5678" yield client + @pytest.fixture def constant_body(): """This is NOT considering the constant body, this should work with the commented line. See https://github.com/Azure/autorest.modelerfour/issues/83 """ - #return Product(child=ChildProduct()) + # return Product(child=ChildProduct()) return Product( child=ChildProduct(), const_child=ConstantProduct(), ) + class TestValidation(object): def test_with_constant_in_path(self, client): @@ -75,84 +75,83 @@ def test_min_length_validation(self, client): try: client.validation_of_method_parameters("1", 100) except ValidationError as err: - assert err.rule == "min_length" - assert err.target == "resource_group_name" + assert err.rule == "min_length" + assert err.target == "resource_group_name" def test_max_length_validation(self, client): try: client.validation_of_method_parameters("1234567890A", 100) except ValidationError as err: - assert err.rule == "max_length" - assert err.target == "resource_group_name" + assert err.rule == "max_length" + assert err.target == "resource_group_name" def test_pattern_validation(self, client): try: client.validation_of_method_parameters("!@#$", 100) except ValidationError as err: - assert err.rule == "pattern" - assert err.target == "resource_group_name" + assert err.rule == "pattern" + assert err.target == "resource_group_name" def test_multiple_validation(self, client): try: client.validation_of_method_parameters("123", 105) except ValidationError as err: - assert err.rule == "multiple" - assert err.target == "id" + assert err.rule == "multiple" + assert err.target == "id" def test_minimum_validation(self, client): try: client.validation_of_method_parameters("123", 0) except ValidationError as err: - assert err.rule == "minimum" - assert err.target == "id" + assert err.rule == "minimum" + assert err.target == "id" def test_maximum_validation(self, client): try: client.validation_of_method_parameters("123", 2000) except ValidationError as err: - assert err.rule == "maximum" - assert err.target == "id" + assert err.rule == "maximum" + assert err.target == "id" def test_minimum_ex_validation(self, client, constant_body): try: constant_body.capacity = 0 client.validation_of_body("123", 150, constant_body) except ValidationError as err: - assert err.rule == "minimum_ex" - assert "capacity" in err.target + assert err.rule == "minimum_ex" + assert "capacity" in err.target def test_maximum_ex_validation(self, client, constant_body): try: constant_body.capacity = 100 client.validation_of_body("123", 150, constant_body) except ValidationError as err: - assert err.rule == "maximum_ex" - assert "capacity" in err.target + assert err.rule == "maximum_ex" + assert "capacity" in err.target def test_max_items_validation(self, client, constant_body): try: - constant_body.display_names = ["item1","item2","item3","item4","item5","item6","item7"] + constant_body.display_names = ["item1", "item2", "item3", "item4", "item5", "item6", "item7"] client.validation_of_body("123", 150, constant_body) except ValidationError as err: - assert err.rule == "max_items" - assert "display_names" in err.target + assert err.rule == "max_items" + assert "display_names" in err.target @pytest.mark.xfail(reason="https://github.com/Azure/autorest.modelerfour/issues/90") def test_api_version_validation(self, client): - client = AutoRestValidationTest( - "abc123", - base_url="http://localhost:3000") + client = AutoRestValidationTest("abc123", base_url="http://localhost:3000") client.api_version = "abc" try: client.validation_of_method_parameters("123", 150) except ValidationError as err: - assert err.rule == "pattern" - assert err.target == "self.api_version" + assert err.rule == "pattern" + assert err.target == "self.api_version" def test_models(self): from validation.models import Error from validation.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_operation_groups(self): @@ -161,5 +160,8 @@ def test_operation_groups(self): with pytest.raises(ImportError): from validation.operations import _auto_rest_validation_test_operations_py3 - from validation.operations._auto_rest_validation_test_operations import AutoRestValidationTestOperationsMixin as AutoRestValidationTestOperationsMixinPy2 + from validation.operations._auto_rest_validation_test_operations import ( + AutoRestValidationTestOperationsMixin as AutoRestValidationTestOperationsMixinPy2, + ) + assert AutoRestValidationTestOperationsMixin == AutoRestValidationTestOperationsMixinPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xml.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xml.py index e2443e5fb9b..57ae7b60bff 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xml.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xml.py @@ -40,14 +40,17 @@ _LOGGER = logging.getLogger(__name__) + @pytest.fixture def client(): with AutoRestSwaggerBATXMLService(base_url="http://localhost:3000") as client: yield client + def _assert_with_log(func, *args, **kwargs): def raise_for_status(response, deserialized, headers): response.http_response.internal_response.raise_for_status() + try: http_response = func(*args, cls=raise_for_status, **kwargs) except Exception as err: @@ -83,14 +86,14 @@ def test_simple(self, client): assert slide2.title == "Overview" assert len(slide2.items) == 3 assert slide2.items[0] == "Why WonderWidgets are great" - assert slide2.items[1] == '' + assert slide2.items[1] == "" assert slide2.items[2] == "Who buys WonderWidgets" _assert_with_log(client.xml.put_simple, slideshow) def test_empty_child_element(self, client): banana = client.xml.get_empty_child_element() - assert banana.flavor == '' # That's the point of this test, it was an empty node. + assert banana.flavor == "" # That's the point of this test, it was an empty node. _assert_with_log(client.xml.put_empty_child_element, banana) def test_empty_root_list(self, client): @@ -121,8 +124,8 @@ def test_get_empty(self, client): def test_wrapped_lists(self, client): bananas = client.xml.get_wrapped_lists() - assert bananas.good_apples == ['Fuji', 'Gala'] - assert bananas.bad_apples == ['Red Delicious'] + assert bananas.good_apples == ["Fuji", "Gala"] + assert bananas.bad_apples == ["Red Delicious"] _assert_with_log(client.xml.put_wrapped_lists, bananas) def test_complex_types(self, client): @@ -150,9 +153,9 @@ def test_list_blobs(self, client): assert blob.properties.content_length == 100 assert blob.properties.content_type == "text/html" # Check that an empty field in the XML is empty string - assert blob.properties.content_encoding == '' + assert blob.properties.content_encoding == "" assert blob.properties.content_language == "en-US" - assert blob.properties.content_md5 == '' + assert blob.properties.content_md5 == "" assert blob.properties.cache_control == "no-cache" assert blob.properties.blob_type == BlobType.block_blob # Check that a field NOT in the XML is None @@ -171,13 +174,14 @@ def test_service_properties(self, client): def test_acls(self, client): acls = client.xml.get_acls() assert len(acls) == 1 - assert acls[0].id == 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' + assert acls[0].id == "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=" _assert_with_log(client.xml.put_acls, acls) def test_models(self): from xmlservice.models import Error from xmlservice.models._models_py3 import Error as ErrorPy3 + assert Error == ErrorPy3 def test_xms_text(self, client): @@ -196,10 +200,10 @@ def test_put_bytes(self, client): def test_get_url(self, client): url_object = client.xml.get_uri() assert isinstance(url_object, ModelWithUrlProperty) - assert url_object.url == 'https://myaccount.blob.core.windows.net/' + assert url_object.url == "https://myaccount.blob.core.windows.net/" def test_put_url(self, client): - client.xml.put_uri('https://myaccount.blob.core.windows.net/') + client.xml.put_uri("https://myaccount.blob.core.windows.net/") def test_operation_groups(self): from xmlservice.operations import XmlOperations @@ -208,4 +212,5 @@ def test_operation_groups(self): from xmlservice.operations import _xml_operations_py3 from xmlservice.operations._xml_operations import XmlOperations as XmlOperationsPy2 + assert XmlOperations == XmlOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xms_error.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xms_error.py index 2d0ffcb20a0..1a159a037d7 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xms_error.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_xms_error.py @@ -30,7 +30,15 @@ from azure.core.exceptions import HttpResponseError, ResourceNotFoundError from xmserrorresponse import XMSErrorResponseExtensions -from xmserrorresponse.models import NotFoundErrorBase, AnimalNotFound, LinkNotFound, PetActionError, PetSadError, PetHungryOrThirstyError +from xmserrorresponse.models import ( + NotFoundErrorBase, + AnimalNotFound, + LinkNotFound, + PetActionError, + PetSadError, + PetHungryOrThirstyError, +) + @pytest.fixture def client(): @@ -45,8 +53,7 @@ def test_get_by_pet_id_success(self, client): pet = client.pet.get_pet_by_id("tommy") assert pet.name == "Tommy Tomson" - client.pet.get_pet_by_id('django') # no fail, 202 - + client.pet.get_pet_by_id("django") # no fail, 202 def test_get_by_pet_id_discriminator(self, client): @@ -100,18 +107,20 @@ def test_error_deserialization_with_param_name_models(self, client): def test_failsafe_deserialize(self, client): from xmserrorresponse.operations._pet_operations import build_do_something_request + request = build_do_something_request(what_action="jump") request.url = client._client.format_url(request.url) pipeline_response = client._client._pipeline.run(request) + class MyPetSadError(PetSadError): def read(self): return b"ignore me" - pipeline_response.context['deserialized_data'] = { + pipeline_response.context["deserialized_data"] = { "reason": "Not OK", "errorMessage": "i should be the message", "errorType": "my own error type", - "actionResponse": "hello" + "actionResponse": "hello", } # add pipeline context with deserialized data and pass to failsafe_deserialize @@ -125,11 +134,11 @@ def read(self): assert error.model.action_response == "hello" assert error.model.error_message == "i should be the message" - def test_models(self): from xmserrorresponse.models import Animal from xmserrorresponse.models._models_py3 import Animal as AnimalPy3 + assert Animal == AnimalPy3 def test_operation_groups(self): @@ -139,4 +148,5 @@ def test_operation_groups(self): from xmserrorresponse.operations import _pet_operations_py3 from xmserrorresponse.operations._pet_operations import PetOperations as PetOperationsPy2 + assert PetOperations == PetOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_zzz.py b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_zzz.py index aaa61ed129d..32f4290cba3 100644 --- a/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_zzz.py +++ b/packages/autorest.python/test/vanilla/legacy/AcceptanceTests/test_zzz.py @@ -44,27 +44,28 @@ def test_ensure_coverage(self): # Please add missing features or failing tests here missing_features_or_bugs = { - 'ConstantsInBody': 1, # https://github.com/Azure/autorest.modelerfour/issues/83 + "ConstantsInBody": 1, # https://github.com/Azure/autorest.modelerfour/issues/83 "ResponsesScenarioF400DefaultModel": 1, "ResponsesScenarioF400DefaultNone": 1, } for name in report: - if name[:3].lower() == 'dpg': + if name[:3].lower() == "dpg": missing_features_or_bugs[name] = 1 # no DPG tests for legacy print("Coverage:") self._print_report(report, not_supported, missing_features_or_bugs) missing_features_or_bugs = { - "putDateTimeMaxLocalNegativeOffset": 1, # Python doesn't support year 1000 - "putDateTimeMinLocalPositiveOffset": 1, # Python doesn't support BC time - 'putDateTimeMaxUtc7MS': 1, # Python doesn't support 7 digits ms datetime - 'FormdataStreamUploadFile': 1, # Form data not supported yet - 'StreamUploadFile': 1, # Form data not supported yet + "putDateTimeMaxLocalNegativeOffset": 1, # Python doesn't support year 1000 + "putDateTimeMinLocalPositiveOffset": 1, # Python doesn't support BC time + "putDateTimeMaxUtc7MS": 1, # Python doesn't support 7 digits ms datetime + "FormdataStreamUploadFile": 1, # Form data not supported yet + "StreamUploadFile": 1, # Form data not supported yet } for name in optional_report: if "Options" in name: - missing_features_or_bugs[name] = 1; # https://github.com/Azure/azure-sdk-for-python/pull/9322 + missing_features_or_bugs[name] = 1 + # https://github.com/Azure/azure-sdk-for-python/pull/9322 if "Multiapi" in name: # multiapi is in a separate test folder missing_features_or_bugs[name] = 1 @@ -74,7 +75,6 @@ def test_ensure_coverage(self): print("Optional coverage:") self._print_report(optional_report, not_supported, missing_features_or_bugs, fail_if_missing=False) - def _print_report(self, report, not_supported=None, missing_features_or_bugs=None, fail_if_missing=True): if not_supported: report.update(not_supported) @@ -91,7 +91,7 @@ def _print_report(self, report, not_supported=None, missing_features_or_bugs=Non print("FAILED TO EXECUTE {0}".format(s)) total_tests = len(report) - warnings.warn ("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) + warnings.warn("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) if fail_if_missing: assert 0 == len(failed) diff --git a/packages/autorest.python/test/vanilla/legacy/doc/conf.py b/packages/autorest.python/test/vanilla/legacy/doc/conf.py index a87a4ce8344..6fc56d95e6f 100644 --- a/packages/autorest.python/test/vanilla/legacy/doc/conf.py +++ b/packages/autorest.python/test/vanilla/legacy/doc/conf.py @@ -18,9 +18,9 @@ # -- Project information ----------------------------------------------------- -project = 'Vanilla Autorest doc' -copyright = '2020, Autorest Python team' -author = 'Autorest Python team' +project = "Vanilla Autorest doc" +copyright = "2020, Autorest Python team" +author = "Autorest Python team" # -- General configuration --------------------------------------------------- @@ -28,32 +28,37 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.doctest', - 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon', - 'sphinx_rtd_theme' +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.doctest", + "sphinx.ext.viewcode", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx_rtd_theme", ] intersphinx_mapping = { # Dependencies - 'python': ('https://docs.python.org/3.8', None), + "python": ("https://docs.python.org/3.8", None), # 'msrestazure': ('http://msrestazure.readthedocs.io/en/latest/', None), # 'msrest': ('http://msrest.readthedocs.io/en/latest/', None), - 'requests': ('https://requests.kennethreitz.org/en/master/', None), - 'aiohttp': ('https://aiohttp.readthedocs.io/en/stable/', None), - 'trio': ('https://trio.readthedocs.io/en/stable/', None), - 'msal': ('https://msal-python.readthedocs.io/en/latest/', None), + "requests": ("https://requests.kennethreitz.org/en/master/", None), + "aiohttp": ("https://aiohttp.readthedocs.io/en/stable/", None), + "trio": ("https://trio.readthedocs.io/en/stable/", None), + "msal": ("https://msal-python.readthedocs.io/en/latest/", None), # Azure packages - 'azure-core': ('https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/1.1.1/', None), - 'azure-identity': ('https://azuresdkdocs.blob.core.windows.net/$web/python/azure-identity/1.1.0/', None), + "azure-core": ("https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/1.1.1/", None), + "azure-identity": ("https://azuresdkdocs.blob.core.windows.net/$web/python/azure-identity/1.1.0/", None), } # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # -- Options for HTML output ------------------------------------------------- @@ -61,9 +66,9 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'sphinx_rtd_theme' +html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] \ No newline at end of file +html_static_path = ["_static"] diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_additional_properties.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_additional_properties.py index e9c27bdecde..85c88f90242 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_additional_properties.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_additional_properties.py @@ -29,96 +29,78 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AdditionalPropertiesClient() as client: await yield_(client) + @pytest.mark.asyncio async def test_create_ap_true(client): input_ap_true = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - }, + "birthdate": "2017-12-13T02:29:51Z", + "complexProperty": {"color": "Red"}, "id": 1, "name": "Puppy", } output_ap_true = await client.pets.create_ap_true(input_ap_true) - assert output_ap_true['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true["birthdate"] == "2017-12-13T02:29:51Z" + @pytest.mark.asyncio async def test_create_cat_ap_true(client): input_ap_true = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': {'color': 'Red'}, - 'id': 1, - 'name': 'Lisa', - 'friendly': True + "birthdate": "2017-12-13T02:29:51Z", + "complexProperty": {"color": "Red"}, + "id": 1, + "name": "Lisa", + "friendly": True, } output_ap_true = await client.pets.create_cat_ap_true(input_ap_true) - assert output_ap_true['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true["birthdate"] == "2017-12-13T02:29:51Z" + @pytest.mark.asyncio async def test_create_ap_object(client): input_ap_obj = { "id": 2, "name": "Hira", - 'siblings': [{ - 'id': 1, - 'name': 'Puppy', - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - }], - 'picture': '//////4=' + "siblings": [ + {"id": 1, "name": "Puppy", "birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}} + ], + "picture": "//////4=", } output_ap_obj = await client.pets.create_ap_object(input_ap_obj) - assert output_ap_obj['siblings'][0]['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_obj["siblings"][0]["birthdate"] == "2017-12-13T02:29:51Z" + @pytest.mark.asyncio async def test_create_ap_string(client): - input_ap_str = { - "id": 3, - "name": 'Tommy', - 'color': 'red', - 'weight': '10 kg', - 'city': 'Bombay' - } + input_ap_str = {"id": 3, "name": "Tommy", "color": "red", "weight": "10 kg", "city": "Bombay"} output_ap_str = await client.pets.create_ap_string(input_ap_str) - assert output_ap_str['color'] == 'red' + assert output_ap_str["color"] == "red" + @pytest.mark.asyncio async def test_create_ap_in_properties(client): - input_ap_int = { - "id": 4, - "name": 'Bunny', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } - } + input_ap_int = {"id": 4, "name": "Bunny", "additionalProperties": {"height": 5.61, "weight": 599, "footsize": 11.5}} output_ap_int = await client.pets.create_ap_in_properties(input_ap_int) - assert output_ap_int['additionalProperties']['weight'] == 599 + assert output_ap_int["additionalProperties"]["weight"] == 599 + @pytest.mark.asyncio async def test_create_ap_in_properties_with_ap_string(client): input_ap_str_add = { "id": 5, - "name": 'Funny', - "@odata.location":'westus', - 'color': 'red', - 'city': 'Seattle', - 'food': 'tikka masala', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } + "name": "Funny", + "@odata.location": "westus", + "color": "red", + "city": "Seattle", + "food": "tikka masala", + "additionalProperties": {"height": 5.61, "weight": 599, "footsize": 11.5}, } output_ap_str_add = await client.pets.create_ap_in_properties_with_ap_string(input_ap_str_add) - assert output_ap_str_add['color'] == 'red' - assert output_ap_str_add['additionalProperties']['weight'] == 599 + assert output_ap_str_add["color"] == "red" + assert output_ap_str_add["additionalProperties"]["weight"] == 599 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_anything.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_anything.py index f9c5902f1ad..351859a3b0c 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_anything.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_anything.py @@ -27,32 +27,39 @@ from async_generator import yield_, async_generator from anythingversiontolerant.aio import AnythingClient + @pytest.fixture @async_generator async def client(): async with AnythingClient() as client: await yield_(client) + @pytest.mark.asyncio async def test_get_string(client): - assert await client.get_string() == 'anything' + assert await client.get_string() == "anything" + @pytest.mark.asyncio async def test_put_string(client): await client.put_string(input="anything") + @pytest.mark.asyncio async def test_get_object(client): assert await client.get_object() == {"message": "An object was successfully returned"} + @pytest.mark.asyncio async def test_put_object(client): - await client.put_object({'foo': 'bar'}) + await client.put_object({"foo": "bar"}) + @pytest.mark.asyncio async def test_get_array(client): - assert await client.get_array() == ['foo', 'bar'] + assert await client.get_array() == ["foo", "bar"] + @pytest.mark.asyncio async def test_put_array(client): - await client.put_array(['foo', 'bar']) + await client.put_array(["foo", "bar"]) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_array.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_array.py index ae2f1e23941..cb87a5f27e0 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_array.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_array.py @@ -36,12 +36,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATArrayService() as client: await yield_(client) + @pytest.fixture def datetimes(): datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") @@ -49,74 +51,98 @@ def datetimes(): datetime3 = isodate.parse_datetime("1492-10-12T10:15:01Z") return [datetime1, datetime2, datetime3] + @pytest.fixture def products(): prod1 = {"integer": 1, "string": "2"} prod2 = {"integer": 3, "string": "4"} prod3 = {"integer": 5, "string": "6"} return [prod1, prod2, prod3] + + @pytest.fixture def listdict(): - return [{"1": "one", "2": "two", "3": "three"}, - {"4": "four", "5": "five", "6": "six"}, - {"7": "seven", "8": "eight", "9": "nine"}] + return [ + {"1": "one", "2": "two", "3": "three"}, + {"4": "four", "5": "five", "6": "six"}, + {"7": "seven", "8": "eight", "9": "nine"}, + ] @pytest.mark.asyncio async def test_empty(client): - assert [] == await client.array.get_empty() + assert [] == await client.array.get_empty() assert await client.array.get_null() is None await client.array.put_empty([]) + @pytest.mark.asyncio async def test_boolean_tfft(client): - assert [True, False, False, True] == await client.array.get_boolean_tfft() + assert [True, False, False, True] == await client.array.get_boolean_tfft() await client.array.put_boolean_tfft([True, False, False, True]) + @pytest.mark.asyncio async def test_integer_valid(client): - assert [1, -1, 3, 300] == await client.array.get_integer_valid() + assert [1, -1, 3, 300] == await client.array.get_integer_valid() await client.array.put_integer_valid([1, -1, 3, 300]) + @pytest.mark.asyncio async def test_long_valid(client): - assert [1, -1, 3, 300] == await client.array.get_long_valid() + assert [1, -1, 3, 300] == await client.array.get_long_valid() await client.array.put_long_valid([1, -1, 3, 300]) + @pytest.mark.asyncio async def test_float_valid(client): - assert [0, -0.01, -1.2e20] == await client.array.get_float_valid() + assert [0, -0.01, -1.2e20] == await client.array.get_float_valid() await client.array.put_float_valid([0, -0.01, -1.2e20]) + @pytest.mark.asyncio async def test_double_valid(client): - assert [0, -0.01, -1.2e20] == await client.array.get_double_valid() + assert [0, -0.01, -1.2e20] == await client.array.get_double_valid() await client.array.put_double_valid([0, -0.01, -1.2e20]) + @pytest.mark.asyncio async def test_string_valid(client): - assert ["foo1", "foo2", "foo3"] == await client.array.get_string_valid() + assert ["foo1", "foo2", "foo3"] == await client.array.get_string_valid() await client.array.put_string_valid(["foo1", "foo2", "foo3"]) + @pytest.mark.asyncio async def test_get_string_with_null(client): - assert ["foo", None, "foo2"] == await client.array.get_string_with_null() + assert ["foo", None, "foo2"] == await client.array.get_string_with_null() + @pytest.mark.asyncio async def test_get_string_with_invalid(client): - assert ["foo", 123, "foo2"] == await client.array.get_string_with_invalid() + assert ["foo", 123, "foo2"] == await client.array.get_string_with_invalid() + @pytest.mark.asyncio async def test_uuid_valid(client): - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"] == await client.array.get_uuid_valid() - await client.array.put_uuid_valid(["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"]) + assert [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] == await client.array.get_uuid_valid() + await client.array.put_uuid_valid( + [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] + ) + @pytest.mark.asyncio async def test_get_uuid_invalid_chars(client): - #Handles invalid characters without error because of no guid class - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == await client.array.get_uuid_invalid_chars() + # Handles invalid characters without error because of no guid class + assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == await client.array.get_uuid_invalid_chars() + @pytest.mark.asyncio async def test_date_valid(client): @@ -125,29 +151,35 @@ async def test_date_valid(client): date3 = isodate.parse_date("1492-10-12") date_array = await client.array.get_date_valid() - assert date_array, [date1, date2 == date3] + assert date_array, [date1, date2 == date3] await client.array.put_date_valid([str(date1), str(date2), str(date3)]) + @pytest.mark.asyncio async def test_date_time_valid(client, datetimes): dt_array = await client.array.get_date_time_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] await client.array.put_date_time_valid([Serializer.serialize_iso(datetime) for datetime in datetimes]) + @pytest.mark.asyncio async def test_date_time_rfc1123_valid(client, datetimes): dt_array = await client.array.get_date_time_rfc1123_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] await client.array.put_date_time_rfc1123_valid([Serializer.serialize_rfc(datetime) for datetime in datetimes]) + @pytest.mark.asyncio async def test_duration_valid(client): duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration2 = timedelta(days=5, hours=1) dur_array = await client.array.get_duration_valid() - assert dur_array, [duration1 == duration2] - await client.array.put_duration_valid([isodate.duration_isoformat(duration1), isodate.duration_isoformat(duration2)]) + assert dur_array, [duration1 == duration2] + await client.array.put_duration_valid( + [isodate.duration_isoformat(duration1), isodate.duration_isoformat(duration2)] + ) + @pytest.mark.asyncio async def test_byte_valid(client): @@ -158,166 +190,197 @@ async def test_byte_valid(client): await client.array.put_byte_valid([b64encode(b).decode() for b in [bytes1, bytes2, bytes3]]) bytes_array = await client.array.get_byte_valid() - assert bytes_array, [bytes1, bytes2 == bytes3] + assert bytes_array, [bytes1, bytes2 == bytes3] + @pytest.mark.asyncio async def test_get_byte_invalid_null(client): bytes_array = await client.array.get_byte_invalid_null() - assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] + assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] + @pytest.mark.asyncio async def test_get_complex_null(client): assert await client.array.get_complex_null() is None + @pytest.mark.asyncio async def test_get_complex_empty(client): - assert [] == await client.array.get_complex_empty() + assert [] == await client.array.get_complex_empty() + @pytest.mark.asyncio async def test_complex_valid(client, products): await client.array.put_complex_valid(products) - assert products == await client.array.get_complex_valid() + assert products == await client.array.get_complex_valid() + @pytest.mark.asyncio async def test_get_array_valid(client): listlist = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] await client.array.put_array_valid(listlist) - assert listlist == await client.array.get_array_valid() + assert listlist == await client.array.get_array_valid() + @pytest.mark.asyncio async def test_dictionary_valid(client, listdict): await client.array.put_dictionary_valid(listdict) - assert listdict == await client.array.get_dictionary_valid() + assert listdict == await client.array.get_dictionary_valid() + @pytest.mark.asyncio async def test_get_complex_item_null(client, products): products_null = [products[0], None, products[2]] - assert products_null == await client.array.get_complex_item_null() + assert products_null == await client.array.get_complex_item_null() + @pytest.mark.asyncio async def test_get_complex_item_empty(client, products): products_empty = [products[0], {}, products[2]] - assert products_empty == await client.array.get_complex_item_empty() + assert products_empty == await client.array.get_complex_item_empty() + @pytest.mark.asyncio async def test_get_array_null(client): assert await client.array.get_array_null() is None + @pytest.mark.asyncio async def test_get_array_empty(client): - assert [] == await client.array.get_array_empty() + assert [] == await client.array.get_array_empty() + @pytest.mark.asyncio async def test_get_array_item_null(client): listlist2 = [["1", "2", "3"], None, ["7", "8", "9"]] - assert listlist2 == await client.array.get_array_item_null() + assert listlist2 == await client.array.get_array_item_null() + @pytest.mark.asyncio async def test_get_array_item_empty(client): listlist3 = [["1", "2", "3"], [], ["7", "8", "9"]] - assert listlist3 == await client.array.get_array_item_empty() + assert listlist3 == await client.array.get_array_item_empty() + @pytest.mark.asyncio async def test_get_dictionary_and_dictionary_item_null(client, listdict): assert await client.array.get_dictionary_null() is None listdict[1] = None - assert listdict == await client.array.get_dictionary_item_null() + assert listdict == await client.array.get_dictionary_item_null() + @pytest.mark.asyncio async def test_get_dictionary_and_dictionary_item_empty(client, listdict): - assert [] == await client.array.get_dictionary_empty() + assert [] == await client.array.get_dictionary_empty() listdict[1] = {} - assert listdict == await client.array.get_dictionary_item_empty() + assert listdict == await client.array.get_dictionary_item_empty() + @pytest.mark.asyncio async def test_array_get_invalid(client): with pytest.raises(DecodeError): await client.array.get_invalid() + @pytest.mark.asyncio async def test_array_get_boolean_invalid_null(client): - assert await client.array.get_boolean_invalid_null(), [True, None == False] + assert await client.array.get_boolean_invalid_null(), [True, None == False] + @pytest.mark.asyncio async def test_array_get_boolean_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert await client.array.get_boolean_invalid_string() == [True, "boolean", False] + @pytest.mark.asyncio async def test_array_get_int_invalid_null(client): - assert await client.array.get_int_invalid_null(), [1, None == 0] + assert await client.array.get_int_invalid_null(), [1, None == 0] + @pytest.mark.asyncio async def test_array_get_int_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert await client.array.get_int_invalid_string() == [1, "integer", 0] + @pytest.mark.asyncio async def test_array_get_long_invalid_null(client): - assert await client.array.get_long_invalid_null(), [1, None == 0] + assert await client.array.get_long_invalid_null(), [1, None == 0] + @pytest.mark.asyncio async def test_array_get_long_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert await client.array.get_long_invalid_string() == [1, "integer", 0] + @pytest.mark.asyncio async def test_array_get_float_invalid_null(client): - assert await client.array.get_float_invalid_null(), [0.0, None == -1.2e20] + assert await client.array.get_float_invalid_null(), [0.0, None == -1.2e20] + @pytest.mark.asyncio async def test_array_get_float_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert await client.array.get_float_invalid_string() == [1, "number", 0] + @pytest.mark.asyncio async def test_array_get_double_invalid_null(client): - assert await client.array.get_double_invalid_null(), [0.0, None == -1.2e20] + assert await client.array.get_double_invalid_null(), [0.0, None == -1.2e20] + @pytest.mark.asyncio async def test_array_get_double_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert await client.array.get_double_invalid_string() == [1, "number", 0] + @pytest.mark.asyncio async def test_array_get_string_with_invalid(client): - assert await client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] + assert await client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] + @pytest.mark.asyncio async def test_array_get_date_invalid_null(client): d_array = await client.array.get_date_invalid_null() - assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] + assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] + @pytest.mark.asyncio async def test_array_get_date_invalid_chars(client): # don't raise deserialization error bc we're not msrest deserializing assert await client.array.get_date_invalid_chars() == ["2011-03-22", "date"] + @pytest.mark.asyncio async def test_array_get_date_time_invalid_null(client): dt_array = await client.array.get_date_time_invalid_null() - assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] + assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] + @pytest.mark.asyncio async def test_array_get_date_time_invalid_chars(client): # don't raise deserialization error bc we're not msrest deserializing - assert await client.array.get_date_time_invalid_chars() == ['2000-12-01t00:00:01z', 'date-time'] + assert await client.array.get_date_time_invalid_chars() == ["2000-12-01t00:00:01z", "date-time"] + @pytest.mark.asyncio async def test_array_get_base64_url(client): - test_array = ['a string that gets encoded with base64url'.encode(), - 'test string'.encode(), - 'Lorem ipsum'.encode()] - assert [deserialize_base64(entry) for entry in await client.array.get_base64_url()] == test_array + test_array = ["a string that gets encoded with base64url".encode(), "test string".encode(), "Lorem ipsum".encode()] + assert [deserialize_base64(entry) for entry in await client.array.get_base64_url()] == test_array + @pytest.mark.asyncio async def test_array_enum_valid(client): array = await client.array.get_enum_valid() await client.array.put_enum_valid(array) + @pytest.mark.asyncio async def test_array_string_enum_valid(client): array = await client.array.get_string_enum_valid() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_binary.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_binary.py index ec52da5fecf..24c02b8b04c 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_binary.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_binary.py @@ -28,6 +28,7 @@ from bodybinaryversiontolerant.aio import BinaryWithContentTypeApplicationJson from azure.core.exceptions import HttpResponseError + @pytest.fixture async def client(): async with BinaryWithContentTypeApplicationJson() as client: @@ -38,10 +39,12 @@ async def client(): async def test_upload_file(client): await client.upload.file(b'{"more": "cowbell"}') + @pytest.mark.asyncio async def test_upload_binary(client): await client.upload.binary(b"Hello, world!") + @pytest.mark.asyncio async def test_error(client): with pytest.raises(HttpResponseError): diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_bool.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_bool.py index 15c83be68b3..bb41cfe8194 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_bool.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_bool.py @@ -30,32 +30,39 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestBoolTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_model_get_true(client): - assert (await client.bool.get_true()) + assert await client.bool.get_true() + @pytest.mark.asyncio async def test_model_get_false(client): assert not (await client.bool.get_false()) + @pytest.mark.asyncio async def test_model_get_null(client): await client.bool.get_null() + @pytest.mark.asyncio async def test_model_put_false(client): await client.bool.put_false() + @pytest.mark.asyncio async def test_model_put_true(client): await client.bool.put_true() + @pytest.mark.asyncio async def test_model_get_invalid(client): with pytest.raises(DecodeError): diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_byte.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_byte.py index 5de2fb5249f..a3bba33a826 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_byte.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_byte.py @@ -29,23 +29,31 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATByteService() as client: await yield_(client) + @pytest.mark.asyncio async def test_non_ascii(client): tests = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x0FB, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) await client.byte.put_non_ascii(serialize_bytearray(tests)) assert tests == deserialize_bytearray(await client.byte.get_non_ascii()) + + @pytest.mark.asyncio async def test_get_null(client): assert await client.byte.get_null() is None + + @pytest.mark.asyncio async def test_get_empty(client): assert bytearray() == deserialize_base64(await client.byte.get_empty()) + + @pytest.mark.asyncio async def test_get_invalid(client): assert await client.byte.get_invalid() == "::::SWAGGER::::" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_client_enum.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_client_enum.py index 920dec297a6..8ae78f3a11b 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_client_enum.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_client_enum.py @@ -26,11 +26,13 @@ import pytest from clientenumversiontolerant import aio, models + @pytest.fixture async def client(): async with aio.ClientWithEnum(x_ms_enum=models.Enum0.SINGLE) as client: yield client + @pytest.mark.asyncio async def test_head(client): await client.head() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_complex.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_complex.py index 1e6ec2acc68..b890e89bfd0 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_complex.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_complex.py @@ -36,36 +36,41 @@ from bodycomplexversiontolerant.aio import AutoRestComplexTestService + class UTC(tzinfo): - def utcoffset(self,dt): - return timedelta(hours=0,minutes=0) + def utcoffset(self, dt): + return timedelta(hours=0, minutes=0) - def tzname(self,dt): + def tzname(self, dt): return "Z" - def dst(self,dt): + def dst(self, dt): return timedelta(0) + import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestComplexTestService() as client: await yield_(client) + @pytest.fixture def min_date(): min_date = datetime.min return min_date.replace(tzinfo=UTC()) + @pytest.mark.asyncio async def test_basic_get_and_put_valid(client): # GET basic/valid basic_result = await client.basic.get_valid() - assert 2 == basic_result['id'] - assert "abc" == basic_result['name'] - assert "YELLOW" == basic_result['color'] + assert 2 == basic_result["id"] + assert "abc" == basic_result["name"] + assert "YELLOW" == basic_result["color"] # PUT basic/valid basic_result = { @@ -75,18 +80,21 @@ async def test_basic_get_and_put_valid(client): } await client.basic.put_valid(basic_result) + @pytest.mark.asyncio async def test_basic_get_empty(client): # GET basic/empty basic_result = await client.basic.get_empty() assert basic_result == {} + @pytest.mark.asyncio async def test_basic_get_null(client): # GET basic/null basic_result = await client.basic.get_null() - assert basic_result['id'] is None - assert basic_result['name'] is None + assert basic_result["id"] is None + assert basic_result["name"] is None + @pytest.mark.asyncio async def test_basic_get_not_provided(client): @@ -94,122 +102,121 @@ async def test_basic_get_not_provided(client): basic_result = await client.basic.get_not_provided() assert basic_result is None + @pytest.mark.asyncio async def test_basic_get_invalid(client): # GET basic/invalid basic_result = await client.basic.get_invalid() # it's deserialized as invalid bc the id is not a number # with legacy, we don't care though - assert basic_result['id'] == 'a' - assert basic_result['name'] == 'abc' + assert basic_result["id"] == "a" + assert basic_result["name"] == "abc" + # COMPLEX TYPE WITH PRIMITIVE PROPERTIES @pytest.mark.asyncio async def test_primitive_get_and_put_int(client): # GET primitive/integer int_result = await client.primitive.get_int() - assert -1 == int_result['field1'] - assert 2 == int_result['field2'] + assert -1 == int_result["field1"] + assert 2 == int_result["field2"] # PUT primitive/integer - int_request = {'field1':-1, 'field2':2} + int_request = {"field1": -1, "field2": 2} await client.primitive.put_int(int_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_long(client): # GET primitive/long long_result = await client.primitive.get_long() - assert 1099511627775 == long_result['field1'] - assert -999511627788 == long_result['field2'] + assert 1099511627775 == long_result["field1"] + assert -999511627788 == long_result["field2"] # PUT primitive/long - long_request = {'field1':1099511627775, 'field2':-999511627788} + long_request = {"field1": 1099511627775, "field2": -999511627788} await client.primitive.put_long(long_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_float(client): # GET primitive/float float_result = await client.primitive.get_float() - assert 1.05 == float_result['field1'] - assert -0.003 == float_result['field2'] + assert 1.05 == float_result["field1"] + assert -0.003 == float_result["field2"] # PUT primitive/float - float_request = { - "field1": 1.05, - "field2": -0.003 - } + float_request = {"field1": 1.05, "field2": -0.003} await client.primitive.put_float(float_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_double(client): # GET primitive/double double_result = await client.primitive.get_double() - assert 3e-100 == double_result['field1'] - assert -5e-57 == double_result['field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose'] + assert 3e-100 == double_result["field1"] + assert ( + -5e-57 + == double_result[ + "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose" + ] + ) # PUT primitive/double double_request = { "field1": 3e-100, - "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose": -5e-57 + "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose": -5e-57, } await client.primitive.put_double(double_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_bool(client): # GET primitive/bool bool_result = await client.primitive.get_bool() - assert bool_result['field_true'] - assert not bool_result['field_false'] + assert bool_result["field_true"] + assert not bool_result["field_false"] # PUT primitive/bool - bool_request = { - "field_true": True, - "field_false": False - } + bool_request = {"field_true": True, "field_false": False} await client.primitive.put_bool(bool_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_string(client): # GET primitive/string string_result = await client.primitive.get_string() - assert "goodrequest" == string_result['field'] - assert "" == string_result['empty'] - assert string_result['null'] is None + assert "goodrequest" == string_result["field"] + assert "" == string_result["empty"] + assert string_result["null"] is None # PUT primitive/string - string_request = { - "null": None, - "empty": "", - "field": "goodrequest" - } + string_request = {"null": None, "empty": "", "field": "goodrequest"} await client.primitive.put_string(string_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_date(client): # GET primitive/date date_result = await client.primitive.get_date() - assert isodate.parse_date("0001-01-01") == isodate.parse_date(date_result['field']) - assert isodate.parse_date("2016-02-29") == isodate.parse_date(date_result['leap']) + assert isodate.parse_date("0001-01-01") == isodate.parse_date(date_result["field"]) + assert isodate.parse_date("2016-02-29") == isodate.parse_date(date_result["leap"]) - date_request = { - "field": '0001-01-01', - "leap": '2016-02-29' - } + date_request = {"field": "0001-01-01", "leap": "2016-02-29"} await client.primitive.put_date(date_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_date_time(client, min_date): # GET primitive/datetime datetime_result = await client.primitive.get_date_time() - assert min_date == Deserializer.deserialize_iso(datetime_result['field']) + assert min_date == Deserializer.deserialize_iso(datetime_result["field"]) - datetime_request = { - "field": "0001-01-01T00:00:00Z", - "now": "2015-05-18T18:38:00Z" - } + datetime_request = {"field": "0001-01-01T00:00:00Z", "now": "2015-05-18T18:38:00Z"} await client.primitive.put_date_time(datetime_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_date_time_rfc1123(client): # GET primitive/datetimerfc1123 @@ -218,159 +225,175 @@ async def test_primitive_get_and_put_date_time_rfc1123(client): # we are not using the min date of year 1 because of the latest msrest update # with msrest update, minimal year we can parse is 100, instead of 1 min_date = datetime(2001, 1, 1) - assert min_date.replace(tzinfo=UTC()) == Deserializer.deserialize_rfc(datetimerfc1123_result['field']) + assert min_date.replace(tzinfo=UTC()) == Deserializer.deserialize_rfc(datetimerfc1123_result["field"]) # we can still model year 1 though with the latest msrest update datetime_request = { "field": Serializer.serialize_rfc(isodate.parse_datetime("0001-01-01T00:00:00Z")), - "now": Serializer.serialize_rfc(isodate.parse_datetime("2015-05-18T11:38:00Z")) + "now": Serializer.serialize_rfc(isodate.parse_datetime("2015-05-18T11:38:00Z")), } await client.primitive.put_date_time_rfc1123(datetime_request) + @pytest.mark.asyncio async def test_primitive_get_and_put_duration(client): # GET primitive/duration expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration_result = await client.primitive.get_duration() - assert expected == Deserializer.deserialize_duration(duration_result['field']) + assert expected == Deserializer.deserialize_duration(duration_result["field"]) await client.primitive.put_duration({"field": Serializer.serialize_duration(expected)}) + @pytest.mark.asyncio async def test_primitive_get_and_put_byte(client): # GET primitive/byte byte_result = await client.primitive.get_byte() valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - assert valid_bytes == bytearray(b64decode(byte_result['field'])) + assert valid_bytes == bytearray(b64decode(byte_result["field"])) # PUT primitive/byte await client.primitive.put_byte({"field": b64encode(valid_bytes).decode()}) + # COMPLEX TYPE WITH READ ONLY PROPERTIES + @pytest.mark.asyncio async def test_readonlyproperty_get_and_put_valid(client): # GET readonly/valid - valid_obj = {"size": 2, 'id': '1234'} + valid_obj = {"size": 2, "id": "1234"} readonly_result = await client.readonlyproperty.get_valid() - assert readonly_result == valid_obj + assert readonly_result == valid_obj # PUT readonly/valid readonly_result = await client.readonlyproperty.put_valid(2) assert readonly_result is None + # COMPLEX TYPE WITH ARRAY PROPERTIES + @pytest.mark.asyncio async def test_array_get_and_put_valid(client): # GET array/valid array_result = await client.array.get_valid() - assert 5 == len(array_result['array']) + assert 5 == len(array_result["array"]) - array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", - "The quick brown fox jumps over the lazy dog"] - assert array_result['array'] == array_value + array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", "The quick brown fox jumps over the lazy dog"] + assert array_result["array"] == array_value # PUT array/valid await client.array.put_valid({"array": array_value}) + @pytest.mark.asyncio async def test_array_get_and_put_empty(client): # GET array/empty array_result = await client.array.get_empty() - assert 0 == len(array_result['array']) + assert 0 == len(array_result["array"]) # PUT array/empty await client.array.put_empty({"array": []}) + @pytest.mark.asyncio async def test_array_get_not_provided(client): # Get array/notprovided assert await client.array.get_not_provided() == {} + # COMPLEX TYPE WITH DICTIONARY PROPERTIES + @pytest.mark.asyncio async def test_dictionary_get_and_put_valid(client): # GET dictionary/valid dict_result = await client.dictionary.get_valid() - assert 5 == len(dict_result['defaultProgram']) + assert 5 == len(dict_result["defaultProgram"]) - dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} - assert dict_val == dict_result['defaultProgram'] + dict_val = {"txt": "notepad", "bmp": "mspaint", "xls": "excel", "exe": "", "": None} + assert dict_val == dict_result["defaultProgram"] # PUT dictionary/valid await client.dictionary.put_valid({"defaultProgram": dict_val}) + @pytest.mark.asyncio async def test_dictionary_get_and_put_empty(client): # GET dictionary/empty dict_result = await client.dictionary.get_empty() - assert 0 == len(dict_result['defaultProgram']) + assert 0 == len(dict_result["defaultProgram"]) # PUT dictionary/empty await client.dictionary.put_empty({"defaultProgram": {}}) + @pytest.mark.asyncio async def test_dictionary_get_and_null(client): # GET dictionary/null - assert (await client.dictionary.get_null())['defaultProgram'] is None + assert (await client.dictionary.get_null())["defaultProgram"] is None + @pytest.mark.asyncio async def test_dictionary_get_not_provided(client): # GET dictionary/notprovided assert await client.dictionary.get_not_provided() == {} + # COMPLEX TYPES THAT INVOLVE INHERITANCE + @pytest.mark.asyncio async def test_inheritance_get_and_put_valid(client): # GET inheritance/valid inheritance_result = await client.inheritance.get_valid() - assert 2 == inheritance_result['id'] - assert "Siameeee" == inheritance_result['name'] - assert -1 == inheritance_result['hates'][1]['id'] - assert "Tomato" == inheritance_result['hates'][1]['name'] + assert 2 == inheritance_result["id"] + assert "Siameeee" == inheritance_result["name"] + assert -1 == inheritance_result["hates"][1]["id"] + assert "Tomato" == inheritance_result["hates"][1]["name"] # PUT inheritance/valid request = { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [{"id": 1, "name": "Potato", "food": "tomato"}, - {"id": -1, "name": "Tomato", "food": "french fries"}] - } + "id": 2, + "name": "Siameeee", + "color": "green", + "breed": "persian", + "hates": [{"id": 1, "name": "Potato", "food": "tomato"}, {"id": -1, "name": "Tomato", "food": "french fries"}], + } await client.inheritance.put_valid(request) + # COMPLEX TYPES THAT INVOLVE POLYMORPHISM + @pytest.mark.asyncio async def test_get_composed_with_discriminator(client): result = await client.polymorphism.get_composed_with_discriminator() - assert result['sampleSalmon']['fish.type'] == "DotSalmon" + assert result["sampleSalmon"]["fish.type"] == "DotSalmon" + @pytest.mark.asyncio async def test_get_composed_without_discriminator(client): result = await client.polymorphism.get_composed_without_discriminator() with pytest.raises(KeyError): - result['sampleSalmon']['fish.type'] # shouldn't have a discriminator + result["sampleSalmon"]["fish.type"] # shouldn't have a discriminator + @pytest.mark.asyncio async def test_polymorphism_get_and_put_valid(client): # GET polymorphism/valid result = await client.polymorphism.get_valid() assert result is not None - assert result['location'] == "alaska" - assert len(result['siblings']) == 3 - assert result['siblings'][0]['fishtype'] == 'shark' - assert result['siblings'][1]['fishtype'] == 'sawshark' - assert result['siblings'][2]['fishtype'] == 'goblin' - assert result['siblings'][0]['age'] == 6 - assert result['siblings'][1]['age'] == 105 - assert result['siblings'][2]['age'] == 1 - + assert result["location"] == "alaska" + assert len(result["siblings"]) == 3 + assert result["siblings"][0]["fishtype"] == "shark" + assert result["siblings"][1]["fishtype"] == "sawshark" + assert result["siblings"][2]["fishtype"] == "goblin" + assert result["siblings"][0]["age"] == 6 + assert result["siblings"][1]["age"] == 105 + assert result["siblings"][2]["age"] == 1 # PUT polymorphism/valid request = { @@ -383,7 +406,7 @@ async def test_polymorphism_get_and_put_valid(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -391,7 +414,7 @@ async def test_polymorphism_get_and_put_valid(client): "length": 10.0, "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" + "picture": "//////4=", }, { "fishtype": "goblin", @@ -400,14 +423,15 @@ async def test_polymorphism_get_and_put_valid(client): "age": 1, "birthday": "2015-08-08T00:00:00.000Z", "jawsize": 5, - "color": "pinkish-gray" - } + "color": "pinkish-gray", + }, ], "location": "alaska", - "iswild": True + "iswild": True, } await client.polymorphism.put_valid(request) + @pytest.mark.asyncio async def test_polymorphism_put_valid_missing_required(client): bad_request = { @@ -420,34 +444,30 @@ async def test_polymorphism_put_valid_missing_required(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "picture": "//////4=" - } + {"fishtype": "sawshark", "species": "dangerous", "length": 10.0, "age": 105, "picture": "//////4="}, ], "location": "alaska", - "iswild": True + "iswild": True, } # in legacy, this raises a ValidationError (when generated with client side validation) with pytest.raises(HttpResponseError) as e: await client.polymorphism.put_valid_missing_required(bad_request) assert "Reached server in scenario: /complex/polymorphism/missingrequired/invalid" in str(e.value.response.text()) + # COMPLEX TYPES THAT INVOLVE RECURSIVE REFERENCE + @pytest.mark.asyncio async def test_polymorphismrecursive_get_and_put_valid(client): # GET polymorphicrecursive/valid result = await client.polymorphicrecursive.get_valid() - assert result['fishtype'] == 'salmon' - assert result['siblings'][0]['fishtype'] == 'shark' - assert result['siblings'][0]['siblings'][0]['fishtype'] == 'salmon' - assert result['siblings'][0]['siblings'][0]['location'] == "atlantic" + assert result["fishtype"] == "salmon" + assert result["siblings"][0]["fishtype"] == "shark" + assert result["siblings"][0]["siblings"][0]["fishtype"] == "salmon" + assert result["siblings"][0]["siblings"][0]["location"] == "atlantic" request = { "fishtype": "salmon", @@ -469,7 +489,7 @@ async def test_polymorphismrecursive_get_and_put_valid(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -477,11 +497,11 @@ async def test_polymorphismrecursive_get_and_put_valid(client): "length": 10.0, "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } + "picture": "//////4=", + }, ], "location": "atlantic", - "iswild": True + "iswild": True, }, { "fishtype": "sawshark", @@ -490,11 +510,11 @@ async def test_polymorphismrecursive_get_and_put_valid(client): "siblings": [], "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } + "picture": "//////4=", + }, ], "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -503,15 +523,16 @@ async def test_polymorphismrecursive_get_and_put_valid(client): "siblings": [], "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } + "picture": "//////4=", + }, ], "location": "alaska", - "iswild": True + "iswild": True, } # PUT polymorphicrecursive/valid await client.polymorphicrecursive.put_valid(request) + @pytest.mark.asyncio async def test_polymorphismrecursive_put_valid_stream(client): path = os.path.abspath( @@ -533,8 +554,10 @@ async def test_polymorphism_get_and_put_complicated(client): smart_salmon = await client.polymorphism.get_complicated() await client.polymorphism.put_complicated(smart_salmon) + # Complex types that uses missing discriminator + @pytest.mark.asyncio async def test_polymorphism_get_and_put_missing_discriminator(client): regular_salmon = { @@ -547,7 +570,7 @@ async def test_polymorphism_get_and_put_missing_discriminator(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -555,7 +578,7 @@ async def test_polymorphism_get_and_put_missing_discriminator(client): "length": 10.0, "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" + "picture": "//////4=", }, { "fishtype": "goblin", @@ -564,19 +587,20 @@ async def test_polymorphism_get_and_put_missing_discriminator(client): "age": 1, "birthday": "2015-08-08T00:00:00.000Z", "jawsize": 5, - "color": "pinkish-gray" - } + "color": "pinkish-gray", + }, ], "location": "alaska", - "iswild": True + "iswild": True, } # Not raise is enough of a test await client.polymorphism.put_missing_discriminator(regular_salmon) # Dot syntax dot_salmon = await client.polymorphism.get_dot_syntax() - assert dot_salmon['fish.type'] == "DotSalmon" - assert dot_salmon['location'] == "sweden" + assert dot_salmon["fish.type"] == "DotSalmon" + assert dot_salmon["location"] == "sweden" + @pytest.mark.asyncio async def test_pass_in_api_version(client): @@ -584,16 +608,17 @@ async def test_pass_in_api_version(client): async with AutoRestComplexTestService(api_version="2021-10-01") as client: assert client._config.api_version == "2021-10-01" + @pytest.mark.asyncio async def test_client_api_version(): api_version = "2021-10-01" + def check_api_version(pipeline_request): assert pipeline_request.http_request.query["api-version"] == "2021-10-01" raise ValueError("succeeded!") async with AutoRestComplexTestService( - api_version=api_version, - policies=[CustomHookPolicy(raw_request_hook=check_api_version)] + api_version=api_version, policies=[CustomHookPolicy(raw_request_hook=check_api_version)] ) as client: basic_result = { "id": 2, diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_config.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_config.py index 00bf1ec45a4..b18c03d8da4 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_config.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_config.py @@ -27,19 +27,22 @@ from azure.core.pipeline.policies import HttpLoggingPolicy from bodystringversiontolerant.aio import AutoRestSwaggerBATService + @pytest.mark.asyncio async def test_http_logging_policy_default(): async with AutoRestSwaggerBATService() as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + @pytest.mark.asyncio async def test_http_logging_policy_custom(): http_logging_policy = HttpLoggingPolicy(base_url="test") http_logging_policy = HttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) async with AutoRestSwaggerBATService(http_logging_policy=http_logging_policy) as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_constants.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_constants.py index 1ffb4872909..12912a7f67d 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_constants.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_constants.py @@ -26,23 +26,24 @@ import pytest from constantsversiontolerant.aio import AutoRestSwaggerConstantService + @pytest.fixture async def client(): async with AutoRestSwaggerConstantService() as client: yield client + def test_put_client_constants(client): client.contants.put_client_constants() assert client._config.header_constant == True assert client._config.query_constant == 100 assert client._config.path_constant == "path" + @pytest.mark.asyncio async def test_put_client_constants_override(): async with AutoRestSwaggerConstantService( - header_constant=False, - query_constant=0, - path_constant="new_path" + header_constant=False, query_constant=0, path_constant="new_path" ) as client: assert client._config.header_constant == False assert client._config.query_constant == 0 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_custom_base_uri.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_custom_base_uri.py index 4b5a71c6752..9494006ec7a 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_custom_base_uri.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_custom_base_uri.py @@ -32,33 +32,39 @@ from custombaseurlmoreoptionsversiontolerant.aio import AutoRestParameterizedCustomHostTestClient import pytest + @pytest.fixture @async_generator async def client(): - async with AutoRestParameterizedHostTestClient("host:3000", retry_total = 0) as client: + async with AutoRestParameterizedHostTestClient("host:3000", retry_total=0) as client: await yield_(client) + @pytest.mark.asyncio async def test_positive(): client = AutoRestParameterizedHostTestClient("host:3000") await client.paths.get_empty("local") + @pytest.mark.asyncio async def test_get_empty_with_bad_string(client): with pytest.raises(ServiceRequestError): await client.paths.get_empty("bad") + @pytest.mark.asyncio async def test_get_empty_with_none(client): with pytest.raises(ValueError): await client.paths.get_empty(None) + @pytest.mark.asyncio async def test_get_empty_from_bad_host(): - async with AutoRestParameterizedHostTestClient("badhost:3000", retry_total = 0) as client: + async with AutoRestParameterizedHostTestClient("badhost:3000", retry_total=0) as client: with pytest.raises(ServiceRequestError): await client.paths.get_empty("local") + @pytest.mark.asyncio async def test_more_options(): async with AutoRestParameterizedCustomHostTestClient("test12", "host:3000") as client: diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_date.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_date.py index 17d90876018..07c6a26f6be 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_date.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_date.py @@ -30,38 +30,45 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDateTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_model_get_and_put_max_date(client): max_date = deserialize_date("9999-12-31T23:59:59.999999Z") await client.date.put_max_date(str(max_date)) assert max_date == deserialize_date(await client.date.get_max_date()) + @pytest.mark.asyncio async def test_model_get_and_put_min_date(client): min_date = deserialize_date("0001-01-01T00:00:00Z") await client.date.put_min_date(str(min_date)) assert min_date == deserialize_date(await client.date.get_min_date()) + @pytest.mark.asyncio async def test_model_get_null(client): assert await client.date.get_null() is None + @pytest.mark.asyncio async def test_model_get_invalid_date(client): assert deserialize_date(await client.date.get_invalid_date()) == datetime.date(2001, 1, 1) + @pytest.mark.asyncio async def test_model_get_overflow_date(client): with pytest.raises(ValueError) as ex: deserialize_date(await client.date.get_overflow_date()) assert "day is out of range for month" in str(ex.value) + @pytest.mark.asyncio async def test_model_get_underflow_date(client): with pytest.raises(ValueError) as ex: diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime.py index c13cb8f93a5..5e468b9b1b3 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime.py @@ -30,21 +30,24 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDateTimeTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_utc_max_date_time(client): max_date = deserialize_datetime("9999-12-31T23:59:59.999Z") dt = deserialize_iso(await client.datetime.get_utc_lowercase_max_date_time()) - assert dt == max_date + assert dt == max_date dt = deserialize_iso(await client.datetime.get_utc_uppercase_max_date_time()) - assert dt == max_date + assert dt == max_date await client.datetime.put_utc_max_date_time(serialize_iso(max_date)) + @pytest.mark.asyncio async def test_utc_max_date_time_7digits(client): max_date = deserialize_datetime("9999-12-31T23:59:59.999999Z") @@ -54,18 +57,22 @@ async def test_utc_max_date_time_7digits(client): # Python doesn't support 7 digits await client.datetime.put_utc_max_date_time7_digits(max_date) + @pytest.mark.asyncio async def test_get_utc_min_date_time(client): min_date = deserialize_datetime("0001-01-01T00:00:00Z") dt = deserialize_iso(await client.datetime.get_utc_min_date_time()) - assert dt == min_date + assert dt == min_date await client.datetime.put_utc_min_date_time(serialize_iso(min_date)) + @pytest.mark.asyncio async def test_get_local_negative_offset_min_date_time(client): await client.datetime.get_local_negative_offset_min_date_time() await client.datetime.put_local_negative_offset_min_date_time( - serialize_iso(deserialize_datetime("0001-01-01T00:00:00-14:00"))) + serialize_iso(deserialize_datetime("0001-01-01T00:00:00-14:00")) + ) + @pytest.mark.asyncio async def test_get_local_no_offset_min_date_time(client): @@ -73,16 +80,19 @@ async def test_get_local_no_offset_min_date_time(client): dt = deserialize_iso(await client.datetime.get_local_no_offset_min_date_time()) assert dt == local_no_offset_min_date_time + @pytest.mark.asyncio async def test_get_local_negative_offset_lowercase_max_date_time(client): with pytest.raises(OverflowError): deserialize_iso(await client.datetime.get_local_negative_offset_lowercase_max_date_time()) + @pytest.mark.asyncio async def test_get_local_negative_offset_uppercase_max_date_time(client): with pytest.raises(OverflowError): deserialize_iso(await client.datetime.get_local_negative_offset_uppercase_max_date_time()) + @pytest.mark.asyncio async def test_local_positive_offset_min_date_time(client): with pytest.raises(OverflowError): @@ -90,36 +100,45 @@ async def test_local_positive_offset_min_date_time(client): with pytest.raises(OverflowError): await client.datetime.put_local_positive_offset_min_date_time( - serialize_iso(deserialize_datetime("0001-01-01T00:00:00+14:00"))) + serialize_iso(deserialize_datetime("0001-01-01T00:00:00+14:00")) + ) + @pytest.mark.asyncio async def test_local_positive_offset_max_date_time(client): await client.datetime.get_local_positive_offset_lowercase_max_date_time() await client.datetime.get_local_positive_offset_uppercase_max_date_time() await client.datetime.put_local_positive_offset_max_date_time( - serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999+14:00"))) + serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999+14:00")) + ) + @pytest.mark.asyncio async def test_get_null(client): await client.datetime.get_null() + @pytest.mark.asyncio async def test_get_overflow(client): with pytest.raises(OverflowError): deserialize_iso(await client.datetime.get_overflow()) + @pytest.mark.asyncio async def test_get_invalid(client): with pytest.raises(ValueError): deserialize_iso(await client.datetime.get_invalid()) + @pytest.mark.asyncio async def test_get_underflow(client): with pytest.raises(ValueError): deserialize_iso(await client.datetime.get_underflow()) + @pytest.mark.asyncio async def test_put_local_negative_offset_max_date_time(client): with pytest.raises(OverflowError): await client.datetime.put_local_negative_offset_max_date_time( - serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999-14:00"))) + serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999-14:00")) + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime_rfc.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime_rfc.py index a9b68797a36..b61502b5a59 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime_rfc.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_datetime_rfc.py @@ -31,31 +31,37 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestRFC1123DateTimeTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_get_null(client): assert await client.datetimerfc1123.get_null() is None + @pytest.mark.asyncio async def test_get_invalid(client): with pytest.raises(isodate.ISO8601Error): deserialize_datetime(await client.datetimerfc1123.get_invalid()) + @pytest.mark.asyncio async def test_get_underflow(client): with pytest.raises(isodate.ISO8601Error): deserialize_datetime(await client.datetimerfc1123.get_underflow()) + @pytest.mark.asyncio async def test_get_overflow(client): with pytest.raises(isodate.ISO8601Error): deserialize_datetime(await client.datetimerfc1123.get_overflow()) + @pytest.mark.asyncio async def test_utc_max_date_time(client): max_date = deserialize_datetime("9999-12-31T23:59:59.999999Z") @@ -64,6 +70,7 @@ async def test_utc_max_date_time(client): await client.datetimerfc1123.get_utc_uppercase_max_date_time() await client.datetimerfc1123.put_utc_max_date_time(serialize_rfc(max_date)) + @pytest.mark.asyncio async def test_utc_min_date_time(client): min_date = deserialize_datetime("0001-01-01T00:00:00Z") diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_dictionary.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_dictionary.py index af881552a1b..0a128bec2fa 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_dictionary.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_dictionary.py @@ -45,175 +45,201 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATDictionaryService() as client: await yield_(client) + @pytest.fixture def test_dict(): test_product1 = {"integer": 1, "string": "2"} test_product2 = {"integer": 3, "string": "4"} test_product3 = {"integer": 5, "string": "6"} - return {"0":test_product1, "1":test_product2, "2":test_product3} + return {"0": test_product1, "1": test_product2, "2": test_product3} + def get_deserialized_dict(response, deserializer): - return { - str(idx): deserializer(response[key]) if response[key] else None - for idx, key in enumerate(response.keys()) - } + return {str(idx): deserializer(response[key]) if response[key] else None for idx, key in enumerate(response.keys())} + def get_serialized_dict(dict, serializer): - return { - k: serializer(v) for k, v in dict.items() - } + return {k: serializer(v) for k, v in dict.items()} + # Primitive types @pytest.mark.asyncio async def test_boolean_tfft(client): - tfft = {"0":True, "1":False, "2":False, "3":True} - assert tfft == await client.dictionary.get_boolean_tfft() + tfft = {"0": True, "1": False, "2": False, "3": True} + assert tfft == await client.dictionary.get_boolean_tfft() await client.dictionary.put_boolean_tfft(tfft) + @pytest.mark.asyncio async def test_get_boolean_invalid(client): - invalid_null_dict = {"0":True, "1":None, "2":False} - assert invalid_null_dict == await client.dictionary.get_boolean_invalid_null() + invalid_null_dict = {"0": True, "1": None, "2": False} + assert invalid_null_dict == await client.dictionary.get_boolean_invalid_null() assert {"0": True, "1": "boolean", "2": False} == await client.dictionary.get_boolean_invalid_string() + @pytest.mark.asyncio async def test_integer_valid(client): - int_valid = {"0":1, "1":-1, "2":3, "3":300} - assert int_valid == await client.dictionary.get_integer_valid() + int_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert int_valid == await client.dictionary.get_integer_valid() await client.dictionary.put_integer_valid(int_valid) + @pytest.mark.asyncio async def test_get_int_invalid(client): - int_null_dict = {"0":1, "1":None, "2":0} - assert int_null_dict == await client.dictionary.get_int_invalid_null() + int_null_dict = {"0": 1, "1": None, "2": 0} + assert int_null_dict == await client.dictionary.get_int_invalid_null() assert {"0": 1, "1": "integer", "2": 0} == await client.dictionary.get_int_invalid_string() + @pytest.mark.asyncio async def test_long_valid(client): - long_valid = {"0":1, "1":-1, "2":3, "3":300} - assert long_valid == await client.dictionary.get_long_valid() + long_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert long_valid == await client.dictionary.get_long_valid() await client.dictionary.put_long_valid(long_valid) + @pytest.mark.asyncio async def test_get_long_invalid(client): - long_null_dict = {"0":1, "1":None, "2":0} - assert long_null_dict == await client.dictionary.get_long_invalid_null() + long_null_dict = {"0": 1, "1": None, "2": 0} + assert long_null_dict == await client.dictionary.get_long_invalid_null() assert {"0": 1, "1": "integer", "2": 0} == await client.dictionary.get_long_invalid_string() + @pytest.mark.asyncio async def test_float_valid(client): - float_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert float_valid == await client.dictionary.get_float_valid() + float_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert float_valid == await client.dictionary.get_float_valid() await client.dictionary.put_float_valid(float_valid) + @pytest.mark.asyncio async def test_get_float_invalid(client): - float_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert float_null_dict == await client.dictionary.get_float_invalid_null() + float_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert float_null_dict == await client.dictionary.get_float_invalid_null() assert {"0": 1, "1": "number", "2": 0} == await client.dictionary.get_float_invalid_string() + @pytest.mark.asyncio async def test_double_valid(client): - double_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert double_valid == await client.dictionary.get_double_valid() + double_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert double_valid == await client.dictionary.get_double_valid() await client.dictionary.put_double_valid(double_valid) + @pytest.mark.asyncio async def test_get_double_invalid(client): - double_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert double_null_dict == await client.dictionary.get_double_invalid_null() + double_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert double_null_dict == await client.dictionary.get_double_invalid_null() assert {"0": 1, "1": "number", "2": 0} == await client.dictionary.get_double_invalid_string() + @pytest.mark.asyncio async def test_string_valid(client): - string_valid = {"0":"foo1", "1":"foo2", "2":"foo3"} - assert string_valid == await client.dictionary.get_string_valid() + string_valid = {"0": "foo1", "1": "foo2", "2": "foo3"} + assert string_valid == await client.dictionary.get_string_valid() await client.dictionary.put_string_valid(string_valid) + @pytest.mark.asyncio async def test_get_string_with_null_and_invalid(client): - string_null_dict = {"0":"foo", "1":None, "2":"foo2"} - string_invalid_dict = {"0":"foo", "1":123, "2":"foo2"} # in version-tolerant, we don't know we should serialize this whole thing as string, so serializes 123 as number - assert string_null_dict == await client.dictionary.get_string_with_null() - assert string_invalid_dict == await client.dictionary.get_string_with_invalid() + string_null_dict = {"0": "foo", "1": None, "2": "foo2"} + string_invalid_dict = { + "0": "foo", + "1": 123, + "2": "foo2", + } # in version-tolerant, we don't know we should serialize this whole thing as string, so serializes 123 as number + assert string_null_dict == await client.dictionary.get_string_with_null() + assert string_invalid_dict == await client.dictionary.get_string_with_invalid() + @pytest.mark.asyncio async def test_date_valid(client): date1 = deserialize_date("2000-12-01T00:00:00Z") date2 = deserialize_date("1980-01-02T00:00:00Z") date3 = deserialize_date("1492-10-12T00:00:00Z") - valid_date_dict = {"0":date1, "1":date2, "2":date3} + valid_date_dict = {"0": date1, "1": date2, "2": date3} date_dictionary = await client.dictionary.get_date_valid() assert get_deserialized_dict(date_dictionary, deserialize_date) == valid_date_dict await client.dictionary.put_date_valid(get_serialized_dict(valid_date_dict, serialize_date)) + @pytest.mark.asyncio async def test_get_date_invalid(client): - date_null_dict = {"0":deserialize_date("2012-01-01"), - "1":None, - "2":deserialize_date("1776-07-04")} + date_null_dict = {"0": deserialize_date("2012-01-01"), "1": None, "2": deserialize_date("1776-07-04")} assert date_null_dict == get_deserialized_dict(await client.dictionary.get_date_invalid_null(), deserialize_date) assert {"0": "2011-03-22", "1": "date"} == await client.dictionary.get_date_invalid_chars() + @pytest.mark.asyncio async def test_date_time_valid(client): datetime1 = deserialize_datetime("2000-12-01T00:00:01Z") datetime2 = deserialize_datetime("1980-01-02T00:11:35+01:00") datetime3 = deserialize_datetime("1492-10-12T10:15:01-08:00") - valid_datetime_dict = {"0":datetime1, "1":datetime2, "2":datetime3} + valid_datetime_dict = {"0": datetime1, "1": datetime2, "2": datetime3} assert valid_datetime_dict == get_deserialized_dict(await client.dictionary.get_date_time_valid(), deserialize_iso) await client.dictionary.put_date_time_valid(get_serialized_dict(valid_datetime_dict, serialize_iso)) + @pytest.mark.asyncio async def test_get_date_time_invalid(client): - datetime_null_dict = {"0":deserialize_datetime("2000-12-01T00:00:01Z"), "1":None} - assert datetime_null_dict == get_deserialized_dict(await client.dictionary.get_date_time_invalid_null(), deserialize_iso) + datetime_null_dict = {"0": deserialize_datetime("2000-12-01T00:00:01Z"), "1": None} + assert datetime_null_dict == get_deserialized_dict( + await client.dictionary.get_date_time_invalid_null(), deserialize_iso + ) assert {"0": "2000-12-01t00:00:01z", "1": "date-time"} == await client.dictionary.get_date_time_invalid_chars() + @pytest.mark.asyncio async def test_date_time_rfc1123_valid(client): rfc_datetime1 = deserialize_datetime("2000-12-01T00:00:01Z") rfc_datetime2 = deserialize_datetime("1980-01-02T00:11:35Z") rfc_datetime3 = deserialize_datetime("1492-10-12T10:15:01Z") - valid_rfc_dict = {"0":rfc_datetime1, "1":rfc_datetime2, "2":rfc_datetime3} + valid_rfc_dict = {"0": rfc_datetime1, "1": rfc_datetime2, "2": rfc_datetime3} - assert valid_rfc_dict == get_deserialized_dict(await client.dictionary.get_date_time_rfc1123_valid(), deserialize_rfc) + assert valid_rfc_dict == get_deserialized_dict( + await client.dictionary.get_date_time_rfc1123_valid(), deserialize_rfc + ) await client.dictionary.put_date_time_rfc1123_valid(get_serialized_dict(valid_rfc_dict, serialize_rfc)) + @pytest.mark.asyncio async def test_get_duration_valid(client): duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration2 = timedelta(days=5, hours=1) - valid_duration_dict = {"0":duration1, "1":duration2} + valid_duration_dict = {"0": duration1, "1": duration2} - assert valid_duration_dict == get_deserialized_dict(await client.dictionary.get_duration_valid(), deserialize_duration) + assert valid_duration_dict == get_deserialized_dict( + await client.dictionary.get_duration_valid(), deserialize_duration + ) await client.dictionary.put_duration_valid(get_serialized_dict(valid_duration_dict, serialize_duration)) + @pytest.mark.asyncio async def test_bytes_valid(client): bytes1 = bytearray([0x0FF, 0x0FF, 0x0FF, 0x0FA]) @@ -221,34 +247,40 @@ async def test_bytes_valid(client): bytes3 = bytearray([0x025, 0x029, 0x043]) bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_valid = {"0":bytes1, "1":bytes2, "2":bytes3} + bytes_valid = {"0": bytes1, "1": bytes2, "2": bytes3} await client.dictionary.put_byte_valid(get_serialized_dict(bytes_valid, serialize_bytearray)) bytes_result = await client.dictionary.get_byte_valid() assert bytes_valid == get_deserialized_dict(bytes_result, deserialize_bytearray) + @pytest.mark.asyncio async def test_get_byte_invalid_null(client): bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_null = {"0":bytes4, "1":None} + bytes_null = {"0": bytes4, "1": None} bytes_result = get_deserialized_dict(await client.dictionary.get_byte_invalid_null(), deserialize_bytearray) - assert bytes_null == bytes_result + assert bytes_null == bytes_result + @pytest.mark.asyncio async def test_get_base64_url(client): - test_dict = {'0': 'a string that gets encoded with base64url'.encode(), - '1': 'test string'.encode(), - '2': 'Lorem ipsum'.encode()} - assert get_deserialized_dict(await client.dictionary.get_base64_url(), deserialize_base64) == test_dict + test_dict = { + "0": "a string that gets encoded with base64url".encode(), + "1": "test string".encode(), + "2": "Lorem ipsum".encode(), + } + assert get_deserialized_dict(await client.dictionary.get_base64_url(), deserialize_base64) == test_dict + # Basic dictionary parsing @pytest.mark.asyncio async def test_empty(client): - assert {} == await client.dictionary.get_empty() + assert {} == await client.dictionary.get_empty() await client.dictionary.put_empty({}) + @pytest.mark.asyncio async def test_get_null_and_invalid(client): assert await client.dictionary.get_null() is None @@ -256,94 +288,104 @@ async def test_get_null_and_invalid(client): with pytest.raises(DecodeError): await client.dictionary.get_invalid() + @pytest.mark.asyncio async def test_get_null_key_and_value(client): # {null:"val1"} is not standard JSON format. C# might work and expects this test to pass, # but we fail and we're happy with it. with pytest.raises(DecodeError): await client.dictionary.get_null_key() - assert {"key1":None} == await client.dictionary.get_null_value() + assert {"key1": None} == await client.dictionary.get_null_value() + @pytest.mark.asyncio async def test_get_empty_string_key(client): - assert {"":"val1"} == await client.dictionary.get_empty_string_key() + assert {"": "val1"} == await client.dictionary.get_empty_string_key() + # Dictionary composed types @pytest.mark.asyncio async def test_get_complex_null_and_empty(client): assert await client.dictionary.get_complex_null() is None - assert {} == await client.dictionary.get_complex_empty() + assert {} == await client.dictionary.get_complex_empty() + @pytest.mark.asyncio async def test_complex_valid(client, test_dict): await client.dictionary.put_complex_valid(test_dict) complex_result = await client.dictionary.get_complex_valid() - assert test_dict == complex_result + assert test_dict == complex_result + @pytest.mark.asyncio async def test_array_valid(client): - list_dict = {"0":["1","2","3"], "1":["4","5","6"], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", "9"]} await client.dictionary.put_array_valid(list_dict) array_result = await client.dictionary.get_array_valid() - assert list_dict == array_result + assert list_dict == array_result + @pytest.mark.asyncio async def test_dictionary_valid(client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{"4":"four","5":"five","6":"six"}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": {"4": "four", "5": "five", "6": "six"}, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } await client.dictionary.put_dictionary_valid(dict_dict) dict_result = await client.dictionary.get_dictionary_valid() - assert dict_dict == dict_result + assert dict_dict == dict_result + @pytest.mark.asyncio async def test_get_complex_null_and_empty(client): assert await client.dictionary.get_complex_null() is None - assert {} == await client.dictionary.get_complex_empty() + assert {} == await client.dictionary.get_complex_empty() + @pytest.mark.asyncio async def test_get_complex_item_null_and_empty(client, test_dict): - test_dict_null = {"0":test_dict["0"], "1":None, "2":test_dict["2"]} + test_dict_null = {"0": test_dict["0"], "1": None, "2": test_dict["2"]} complex_result = await client.dictionary.get_complex_item_null() - assert complex_result == test_dict_null + assert complex_result == test_dict_null - test_dict_empty = {"0":test_dict["0"], "1": {}, "2":test_dict["2"]} + test_dict_empty = {"0": test_dict["0"], "1": {}, "2": test_dict["2"]} complex_result = await client.dictionary.get_complex_item_empty() - assert complex_result == test_dict_empty + assert complex_result == test_dict_empty + @pytest.mark.asyncio async def test_get_array_empty(client): assert await client.dictionary.get_array_null() is None - assert {} == await client.dictionary.get_array_empty() + assert {} == await client.dictionary.get_array_empty() + @pytest.mark.asyncio async def test_get_array_item_null_and_empty(client): - list_dict = {"0":["1","2","3"], "1":None, "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": None, "2": ["7", "8", "9"]} array_result = await client.dictionary.get_array_item_null() - assert list_dict == array_result + assert list_dict == array_result - list_dict = {"0":["1","2","3"], "1":[], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": [], "2": ["7", "8", "9"]} array_result = await client.dictionary.get_array_item_empty() - assert list_dict == array_result + assert list_dict == array_result + @pytest.mark.asyncio async def test_get_dictionary_null_and_empty(client): assert await client.dictionary.get_dictionary_null() is None - assert {} == await client.dictionary.get_dictionary_empty() + assert {} == await client.dictionary.get_dictionary_empty() + @pytest.mark.asyncio async def test_get_dictionary_item_null_and_empty(client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":None, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = {"0": {"1": "one", "2": "two", "3": "three"}, "1": None, "2": {"7": "seven", "8": "eight", "9": "nine"}} dict_result = await client.dictionary.get_dictionary_item_null() - assert dict_dict == dict_result + assert dict_dict == dict_result - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = {"0": {"1": "one", "2": "two", "3": "three"}, "1": {}, "2": {"7": "seven", "8": "eight", "9": "nine"}} dict_result = await client.dictionary.get_dictionary_item_empty() - assert dict_dict == dict_result + assert dict_dict == dict_result diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_duration.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_duration.py index beab8aa84e2..b7b02ff8af5 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_duration.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_duration.py @@ -33,12 +33,14 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestDurationTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_get_null_and_invalid(client): assert await client.duration.get_null() is None @@ -46,7 +48,12 @@ async def test_get_null_and_invalid(client): with pytest.raises(isodate.ISO8601Error): deserialize_duration(await client.duration.get_invalid()) + @pytest.mark.asyncio async def test_positive_duration(client): - assert isodate.Duration(4, 45005, 0, years=3, months=6) == deserialize_duration(await client.duration.get_positive_duration()) - await client.duration.put_positive_duration(serialize_duration(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11))) + assert isodate.Duration(4, 45005, 0, years=3, months=6) == deserialize_duration( + await client.duration.get_positive_duration() + ) + await client.duration.put_positive_duration( + serialize_duration(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_error_with_secrets.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_error_with_secrets.py index b0a5b6e5ef8..3ce5b0d5f49 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_error_with_secrets.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_error_with_secrets.py @@ -28,21 +28,24 @@ from errorwithsecretsversiontolerant.aio import ErrorWithSecrets from azure.core.exceptions import HttpResponseError + @pytest.fixture async def client(): async with ErrorWithSecrets() as client: yield client + @pytest.mark.asyncio async def test_create_secret(client): request = build_error_with_secrets_create_secret_request( headers={"authorization": "SharedKey 1c88a67921784300a462b2cb61da2339"}, params={"key": "1c88a67921784300a462b2cb61da2339"}, - json={ "key": "1c88a67921784300a462b2cb61da2339" }, + json={"key": "1c88a67921784300a462b2cb61da2339"}, ) response = await client.send_request(request) response.raise_for_status() + @pytest.mark.asyncio async def test_raise_error_with_secrets(client): with pytest.raises(HttpResponseError) as ex: diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_extensible_enums.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_extensible_enums.py index 37bf421bddf..63c7625cf58 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_extensible_enums.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_extensible_enums.py @@ -28,38 +28,37 @@ import pytest + @pytest.fixture @async_generator async def client(): async with PetStoreInc() as client: await yield_(client) + @pytest.mark.asyncio async def test_get_by_pet_id(client): # Now enum return are always string (Autorest.Python 3.0) - tommy = await client.pet.get_by_pet_id('tommy') - assert tommy["DaysOfWeek"] == "Monday" - assert tommy["IntEnum"] == "1" + tommy = await client.pet.get_by_pet_id("tommy") + assert tommy["DaysOfWeek"] == "Monday" + assert tommy["IntEnum"] == "1" - casper = await client.pet.get_by_pet_id('casper') - assert casper["DaysOfWeek"] == "Weekend" - assert casper["IntEnum"] == "2" + casper = await client.pet.get_by_pet_id("casper") + assert casper["DaysOfWeek"] == "Weekend" + assert casper["IntEnum"] == "2" - scooby = await client.pet.get_by_pet_id('scooby') - assert scooby["DaysOfWeek"] == "Thursday" + scooby = await client.pet.get_by_pet_id("scooby") + assert scooby["DaysOfWeek"] == "Thursday" # https://github.com/Azure/autorest.csharp/blob/e5f871b7433e0f6ca6a17307fba4a2cfea4942b4/test/vanilla/AcceptanceTests.cs#L429 # "allowedValues" of "x-ms-enum" is not supported in Python - assert scooby["IntEnum"] == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" + assert scooby["IntEnum"] == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" + @pytest.mark.asyncio async def test_add_pet(client): - retriever = { - "name": "Retriever", - "IntEnum": "3", - "DaysOfWeek": "Friday" - } + retriever = {"name": "Retriever", "IntEnum": "3", "DaysOfWeek": "Friday"} returned_pet = await client.pet.add_pet(retriever) - assert returned_pet["DaysOfWeek"] == "Friday" - assert returned_pet["IntEnum"] == "3" - assert returned_pet['name'] == "Retriever" + assert returned_pet["DaysOfWeek"] == "Friday" + assert returned_pet["IntEnum"] == "3" + assert returned_pet["name"] == "Retriever" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_file.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_file.py index 27e6074bc2d..e103fdfb714 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_file.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_file.py @@ -38,13 +38,12 @@ @pytest.fixture @async_generator async def client(connection_data_block_size=None): - async with AutoRestSwaggerBATFileService( - connection_data_block_size=connection_data_block_size - ) as client: + async with AutoRestSwaggerBATFileService(connection_data_block_size=connection_data_block_size) as client: await yield_(client) + @pytest.mark.asyncio -@pytest.mark.parametrize('client', [1000], indirect=True) +@pytest.mark.parametrize("client", [1000], indirect=True) async def test_get_file(client): file_length = 0 with io.BytesIO() as file_handle: @@ -54,18 +53,31 @@ async def test_get_file(client): file_length += len(data) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) - - with open(sample_file, 'rb') as data: + join( + cwd, + pardir, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) + + with open(sample_file, "rb") as data: sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) + assert sample_data == hash(file_handle.getvalue()) + @pytest.mark.asyncio -@pytest.mark.parametrize('client', [4096], indirect=True) +@pytest.mark.parametrize("client", [4096], indirect=True) async def test_get_empty_file(client): file_length = 0 with io.BytesIO() as file_handle: @@ -75,10 +87,11 @@ async def test_get_empty_file(client): file_length += len(data) file_handle.write(data) - assert file_length == 0 + assert file_length == 0 + @pytest.mark.asyncio -@pytest.mark.parametrize('client', [4096], indirect=True) +@pytest.mark.parametrize("client", [4096], indirect=True) async def test_files_long_running(client): file_length = 0 stream = await client.files.get_file_large() @@ -86,5 +99,4 @@ async def test_files_long_running(client): assert 0 < len(data) <= 4096 file_length += len(data) - assert file_length == 3000 * 1024 * 1024 - + assert file_length == 3000 * 1024 * 1024 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_form_data.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_form_data.py index 4adc82a9390..be4e4ac6da2 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_form_data.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_form_data.py @@ -32,21 +32,23 @@ import pytest + @pytest.fixture def dummy_file(): - with tempfile.NamedTemporaryFile(mode='w', delete=False) as dummy: + with tempfile.NamedTemporaryFile(mode="w", delete=False) as dummy: dummy.write("Test file") # Get outside of the "with", so file can be re-opened on Windows yield dummy.name os.remove(dummy.name) + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATFormDataService( - connection_data_block_size = 2, - retry_total = 50, # Be agressive on this test, sometimes testserver DDOS :-p - retry_backoff_factor = 1.6 + connection_data_block_size=2, + retry_total=50, # Be agressive on this test, sometimes testserver DDOS :-p + retry_backoff_factor=1.6, ) as client: await yield_(client) @@ -54,17 +56,15 @@ async def client(): @pytest.mark.asyncio async def test_file_upload_stream(client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: - files = { - "file_content": stream_data, - "file_name": "UploadFile.txt" - } + files = {"file_content": stream_data, "file_name": "UploadFile.txt"} resp = await client.formdata.upload_file(files) async for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string + @pytest.mark.asyncio async def test_file_upload_stream_raw(client): @@ -72,31 +72,27 @@ def test_callback(response, data, headers): return data test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: - files = { - "file_content": stream_data, - "file_name": "UploadFile.txt" - } + files = {"file_content": stream_data, "file_name": "UploadFile.txt"} resp = await client.formdata.upload_file(files, cls=test_callback) async for data in resp: result.write(data) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string + @pytest.mark.asyncio async def test_file_upload_file_stream(client, dummy_file): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - files = { - "file_content": upload_data, - "file_name": name - } + with open(dummy_file, "rb") as upload_data: + files = {"file_content": upload_data, "file_name": name} resp = await client.formdata.upload_file(files) async for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" + @pytest.mark.asyncio async def test_file_upload_file_stream_raw(client, dummy_file): @@ -106,39 +102,38 @@ def test_callback(response, data, headers): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - files = { - "file_content": upload_data, - "file_name": name - } + with open(dummy_file, "rb") as upload_data: + files = {"file_content": upload_data, "file_name": name} resp = await client.formdata.upload_file(files, cls=test_callback) async for data in resp: result.write(data) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" + @pytest.mark.asyncio async def test_file_body_upload(client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = await client.formdata.upload_file_via_body(stream_data) async for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = await client.formdata.upload_file_via_body(upload_data) async for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" + @pytest.mark.asyncio async def test_file_body_upload_generator(client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") @async_generator async def stream_upload(data, length, block_size): @@ -146,7 +141,7 @@ async def stream_upload(data, length, block_size): while True: block = data.read(block_size) progress += len(block) - print("Progress... {}%".format(int(progress*100/length))) + print("Progress... {}%".format(int(progress * 100 / length))) if not block: break await yield_(block) @@ -157,12 +152,12 @@ async def stream_upload(data, length, block_size): resp = await client.formdata.upload_file_via_body(streamed_upload) async for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: streamed_upload = stream_upload(upload_data, len("Test file"), 2) response = await client.formdata.upload_file_via_body(streamed_upload) async for data in response: result.write(data) - assert result.getvalue().decode() == "Test file" \ No newline at end of file + assert result.getvalue().decode() == "Test file" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_header.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_header.py index 04ea2edf16f..f421975b96a 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_header.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_header.py @@ -31,18 +31,22 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATHeaderService() as client: await yield_(client) + @pytest.fixture def value_header(): def _value_header(response, _, headers): return headers.get("value") + return _value_header + @pytest.mark.asyncio async def test_integer(client, value_header): await client.header.param_integer(scenario="positive", value=1) @@ -54,6 +58,7 @@ async def test_integer(client, value_header): response = await client.header.response_integer(scenario="negative", cls=value_header) assert response == -2 + @pytest.mark.asyncio async def test_long(client, value_header): await client.header.param_long(scenario="positive", value=105) @@ -64,6 +69,7 @@ async def test_long(client, value_header): response = await client.header.response_long(scenario="negative", cls=value_header) assert response == -2 + @pytest.mark.asyncio async def test_float(client, value_header): await client.header.param_float(scenario="positive", value=0.07) @@ -74,6 +80,7 @@ async def test_float(client, value_header): response = await client.header.response_float(scenario="negative", cls=value_header) assert abs(-3.0 - response) < 0.00001 + @pytest.mark.asyncio async def test_double(client, value_header): await client.header.param_double(scenario="positive", value=7e120) @@ -84,6 +91,7 @@ async def test_double(client, value_header): response = await client.header.response_double(scenario="negative", cls=value_header) assert response == -3.0 + @pytest.mark.asyncio async def test_bool(client, value_header): await client.header.param_bool(scenario="true", value=True) @@ -94,6 +102,7 @@ async def test_bool(client, value_header): response = await client.header.response_bool(scenario="false", cls=value_header) assert response == False + @pytest.mark.asyncio async def test_string(client, value_header): await client.header.param_string(scenario="valid", value="The quick brown fox jumps over the lazy dog") @@ -107,13 +116,14 @@ async def test_string(client, value_header): response = await client.header.response_string(scenario="empty", cls=value_header) assert response is None + @pytest.mark.asyncio async def test_enum(client, value_header): - await client.header.param_enum(scenario="valid", value='GREY') + await client.header.param_enum(scenario="valid", value="GREY") await client.header.param_enum(scenario="null", value=None) response = await client.header.response_enum(scenario="valid", cls=value_header) - assert response == 'GREY' + assert response == "GREY" # We receive an empty string. # Starting msrest 0.4.22, we consider that if a string is not in the enum, this not @@ -123,6 +133,7 @@ async def test_enum(client, value_header): response = await client.header.response_enum(scenario="null", cls=value_header) assert response is None + @pytest.mark.asyncio async def test_date(client, value_header): await client.header.param_date(scenario="valid", value=isodate.parse_date("2010-01-01")) @@ -133,6 +144,7 @@ async def test_date(client, value_header): response = await client.header.response_date(scenario="min", cls=value_header) assert response == isodate.parse_date("0001-01-01") + @pytest.mark.asyncio async def test_datetime(client, value_header): await client.header.param_datetime(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) @@ -143,6 +155,7 @@ async def test_datetime(client, value_header): response = await client.header.response_datetime(scenario="min", cls=value_header) assert response == isodate.parse_datetime("0001-01-01T00:00:00Z") + @pytest.mark.asyncio async def test_datetime_rfc(client, value_header): await client.header.param_datetime_rfc1123(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) @@ -156,16 +169,20 @@ async def test_datetime_rfc(client, value_header): response = await client.header.response_datetime_rfc1123(scenario="min", cls=value_header) assert response == isodate.parse_datetime("2001-01-01T00:00:00Z") + @pytest.mark.asyncio async def test_duration(client, value_header): - await client.header.param_duration(scenario="valid", value=timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) + await client.header.param_duration( + scenario="valid", value=timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) + ) response = await client.header.response_duration(scenario="valid", cls=value_header) assert response == timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) + @pytest.mark.asyncio async def test_byte(client, value_header): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") await client.header.param_byte(scenario="valid", value=u_bytes) response = await client.header.response_byte(scenario="valid", cls=value_header) @@ -173,28 +190,34 @@ async def test_byte(client, value_header): await client.header.param_existing_key(user_agent_parameter="overwrite") + @pytest.mark.asyncio async def test_response_existing_key(client): def useragent_header(response, _, headers): - return headers.get('User-Agent') + return headers.get("User-Agent") + response = await client.header.response_existing_key(cls=useragent_header) assert response == "overwrite" + @pytest.mark.asyncio async def test_response_protected_key(client): # This test is only valid for C#, which content-type can't be override this way - #await client.header.param_protected_key("text/html") + # await client.header.param_protected_key("text/html") # This test has different result compare to C#, which content-type is saved in another place. def content_header(response, _, headers): - return headers.get('Content-Type') + return headers.get("Content-Type") + response = await client.header.response_protected_key(cls=content_header) assert response == "text/html; charset=utf-8" + @pytest.mark.asyncio async def test_custom_request_id(client): def status_code(pipeline_response, _, headers): return pipeline_response.http_response.status_code + custom_headers = {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} response = await client.header.custom_request_id(headers=custom_headers, cls=status_code) assert response == 200 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_hooks.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_hooks.py index 20323e8b110..e080a2ca651 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_hooks.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_hooks.py @@ -27,14 +27,17 @@ from azure.core.pipeline.policies import CustomHookPolicy from bodyarrayversiontolerant.aio import AutoRestSwaggerBATArrayService + def is_rest(obj): return hasattr(obj, "content") + def raw_request_callback(request): assert is_rest(request.http_request) assert hasattr(request.http_request, "set_multipart_mixed") raise ValueError("I entered the callback!") + @pytest.mark.asyncio async def test_raw_request_hook(): raw_request_hook_policy = CustomHookPolicy(raw_request_hook=raw_request_callback) @@ -43,20 +46,24 @@ async def test_raw_request_hook(): await client.array.get_array_empty() assert "I entered the callback!" in str(ex.value) + @pytest.mark.asyncio async def test_raw_request_hook_send_request(): from bodyarrayversiontolerant.operations._operations import build_array_get_array_empty_request + raw_request_hook_policy = CustomHookPolicy(raw_request_hook=raw_request_callback) async with AutoRestSwaggerBATArrayService(policies=[raw_request_hook_policy]) as client: with pytest.raises(ValueError) as ex: await client.send_request(build_array_get_array_empty_request()) assert "I entered the callback!" in str(ex.value) + def raw_response_callback(response): assert is_rest(response.http_response) assert hasattr(response.http_response, "parts") raise ValueError("I entered the callback!") + @pytest.mark.asyncio async def test_raw_response_hook(): raw_response_hook_policy = CustomHookPolicy(raw_response_hook=raw_response_callback) @@ -65,9 +72,11 @@ async def test_raw_response_hook(): await client.array.get_array_empty() assert "I entered the callback!" in str(ex.value) + @pytest.mark.asyncio async def test_raw_response_hook_send_request(): from bodyarrayversiontolerant.operations._operations import build_array_get_array_empty_request + raw_response_hook_policy = CustomHookPolicy(raw_response_hook=raw_response_callback) async with AutoRestSwaggerBATArrayService(policies=[raw_response_hook_policy]) as client: with pytest.raises(ValueError) as ex: diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_http.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_http.py index 1709c4b47ff..b32a4ae5d59 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_http.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_http.py @@ -41,13 +41,7 @@ @async_generator async def client(cookie_policy): """Create a AutoRestHttpInfrastructureTestService client with test server credentials.""" - policies = [ - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRedirectPolicy(), - AsyncRetryPolicy(), - cookie_policy - ] + policies = [HeadersPolicy(), ContentDecodePolicy(), AsyncRedirectPolicy(), AsyncRetryPolicy(), cookie_policy] async with AutoRestHttpInfrastructureTestService(policies=policies) as client: await yield_(client) @@ -56,10 +50,12 @@ async def assert_status(code, func, *args, **kwargs): def return_status(pipeline_response, data, headers): assert isinstance(pipeline_response, PipelineResponse) return pipeline_response.http_response.status_code - kwargs['cls'] = return_status + + kwargs["cls"] = return_status status_code = await func(*args, **kwargs) assert status_code == code + async def assert_raises_with_message(msg, func, *args, **kwargs): try: await func(*args, **kwargs) @@ -68,6 +64,7 @@ async def assert_raises_with_message(msg, func, *args, **kwargs): except HttpResponseError as err: assert err.message == msg + async def assert_raises_with_model(code, model, func, *args, **kwargs): try: await func(*args, **kwargs) @@ -78,6 +75,7 @@ async def assert_raises_with_model(code, model, func, *args, **kwargs): assert isinstance(err.model, model) assert err.response.status_code == code + async def assert_raises_with_status(code, func, *args, **kwargs): try: await func(*args, **kwargs) @@ -87,6 +85,7 @@ async def assert_raises_with_status(code, func, *args, **kwargs): assert err.response.status_code == code + async def assert_raises_with_status_and_message(status_code, message, func, *args, **kwargs): try: await func(*args, **kwargs) @@ -94,7 +93,8 @@ async def assert_raises_with_status_and_message(status_code, message, func, *arg except HttpResponseError as err: assert err.status_code == status_code - assert err.response.json()['message'] == message + assert err.response.json()["message"] == message + async def assert_raises_with_status_and_response_contains(code, msg, func, *args, **kwargs): try: @@ -105,21 +105,22 @@ async def assert_raises_with_status_and_response_contains(code, msg, func, *args assert err.response.status_code == code assert msg in err.response.text() + @pytest.mark.asyncio async def test_get200_model204(client): r = await client.multiple_responses.get200_model204_no_model_default_error200_valid() - assert '200' == r['statusCode'] + assert "200" == r["statusCode"] - await assert_raises_with_status(201, - client.multiple_responses.get200_model204_no_model_default_error201_invalid) + await assert_raises_with_status(201, client.multiple_responses.get200_model204_no_model_default_error201_invalid) - await assert_raises_with_status(202, - client.multiple_responses.get200_model204_no_model_default_error202_none) + await assert_raises_with_status(202, client.multiple_responses.get200_model204_no_model_default_error202_none) assert await client.multiple_responses.get200_model204_no_model_default_error204_valid() is None - await assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model204_no_model_default_error400_valid) + await assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model204_no_model_default_error400_valid + ) + @pytest.mark.asyncio async def test_get200_model201(client): @@ -127,44 +128,47 @@ async def test_get200_model201(client): b_model = await client.multiple_responses.get200_model201_model_default_error201_valid() assert b_model is not None - assert b_model['statusCode'] == "201" - assert b_model['textStatusCode'] == "Created" + assert b_model["statusCode"] == "201" + assert b_model["textStatusCode"] == "Created" + + await assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model201_model_default_error400_valid + ) - await assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model201_model_default_error400_valid) @pytest.mark.asyncio async def test_get200_model_a201_model_c404(client): a_model = await client.multiple_responses.get200_model_a201_model_c404_model_d_default_error200_valid() assert a_model is not None - assert a_model['statusCode'] == "200" + assert a_model["statusCode"] == "200" c_model = await client.multiple_responses.get200_model_a201_model_c404_model_d_default_error201_valid() assert c_model is not None - assert c_model['httpCode'] == "201" + assert c_model["httpCode"] == "201" - await assert_status(404, - client.multiple_responses.get200_model_a201_model_c404_model_d_default_error404_valid) + await assert_status(404, client.multiple_responses.get200_model_a201_model_c404_model_d_default_error404_valid) + + await assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid + ) - await assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid) @pytest.mark.asyncio async def test_get202_none204(client): await client.multiple_responses.get202_none204_none_default_error202_none() await client.multiple_responses.get202_none204_none_default_error204_none() - await assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get202_none204_none_default_error400_valid) + await assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get202_none204_none_default_error400_valid + ) await client.multiple_responses.get202_none204_none_default_none202_invalid() await client.multiple_responses.get202_none204_none_default_none204_none() - await assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_none) + await assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_none) + + await assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_invalid) - await assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_invalid) @pytest.mark.asyncio async def test_get_default_model_a200(client): @@ -174,27 +178,27 @@ async def test_get_default_model_a200(client): await client.multiple_responses.get_default_model_a200_valid() await client.multiple_responses.get_default_model_a200_none() + @pytest.mark.skip(reason="Not generating with models yet") @pytest.mark.asyncio async def test_get_default_model_a400(client): - await assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_valid) + await assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_valid) + + await assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_none) - await assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_none) @pytest.mark.asyncio async def test_get_default_none200(client): await client.multiple_responses.get_default_none200_invalid() await client.multiple_responses.get_default_none200_none() + @pytest.mark.asyncio async def test_get_default_none400(client): - await assert_raises_with_status(400, - client.multiple_responses.get_default_none400_invalid) + await assert_raises_with_status(400, client.multiple_responses.get_default_none400_invalid) + + await assert_raises_with_status(400, client.multiple_responses.get_default_none400_none) - await assert_raises_with_status(400, - client.multiple_responses.get_default_none400_none) @pytest.mark.asyncio async def test_get200_model_a200(client): @@ -202,187 +206,183 @@ async def test_get200_model_a200(client): await assert_status(200, client.multiple_responses.get200_model_a200_valid) - await assert_status(200, client.multiple_responses.get200_model_a200_invalid) # in legacy it's supposed to deserialized as exception model "MyException" + await assert_status( + 200, client.multiple_responses.get200_model_a200_invalid + ) # in legacy it's supposed to deserialized as exception model "MyException" + @pytest.mark.asyncio async def test_get200_model_a400(client): - await assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_none) - await assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_valid) - await assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_invalid) + await assert_raises_with_status(400, client.multiple_responses.get200_model_a400_none) + await assert_raises_with_status(400, client.multiple_responses.get200_model_a400_valid) + await assert_raises_with_status(400, client.multiple_responses.get200_model_a400_invalid) + @pytest.mark.asyncio async def test_get200_model_a202(client): - await assert_raises_with_status(202, - client.multiple_responses.get200_model_a202_valid) + await assert_raises_with_status(202, client.multiple_responses.get200_model_a202_valid) + @pytest.mark.asyncio async def test_server_error_status_codes_501(client): - await assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.head501) + await assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.head501) + + await assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.get501) - await assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.get501) @pytest.mark.asyncio async def test_server_error_status_codes_505(client): - await assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.post505) + await assert_raises_with_status(requests.codes.http_version_not_supported, client.http_server_failure.post505) + + await assert_raises_with_status(requests.codes.http_version_not_supported, client.http_server_failure.delete505) - await assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.delete505) @pytest.mark.asyncio async def test_retry_status_codes_408(client): await client.http_retry.head408() + @pytest.mark.asyncio async def test_retry_status_codes_502(client): await client.http_retry.get502() await client.http_retry.options502() + @pytest.mark.asyncio async def test_retry_status_codes_500(client): await client.http_retry.put500() await client.http_retry.patch500() + @pytest.mark.asyncio async def test_retry_status_codes_503(client): await client.http_retry.post503() await client.http_retry.delete503() + @pytest.mark.asyncio async def test_retry_status_codes_504(client): await client.http_retry.put504() await client.http_retry.patch504() + @pytest.mark.asyncio async def test_error_status_codes_400(client): - await assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.head400) + await assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.head400) - await assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.get400) + await assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.get400) # TODO, 4042586: Support options operations in swagger modeler - #assert_raises_with_status(requests.codes.bad_request, + # assert_raises_with_status(requests.codes.bad_request, # await client.http_client_failure.options400) - await assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.put400) + await assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.put400) + + await assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.patch400) - await assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.patch400) + await assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.post400) - await assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.post400) + await assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.delete400) - await assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.delete400) @pytest.mark.asyncio async def test_error_status_codes_401(client): - await assert_raises_with_status(requests.codes.unauthorized, - client.http_client_failure.head401) + await assert_raises_with_status(requests.codes.unauthorized, client.http_client_failure.head401) + @pytest.mark.asyncio async def test_error_status_codes_402(client): - await assert_raises_with_status(requests.codes.payment_required, - client.http_client_failure.get402) + await assert_raises_with_status(requests.codes.payment_required, client.http_client_failure.get402) + @pytest.mark.asyncio async def test_error_status_codes_403(client): # TODO, 4042586: Support options operations in swagger modeler - #assert_raises_with_status(requests.codes.forbidden, + # assert_raises_with_status(requests.codes.forbidden, # await client.http_client_failure.options403) - await assert_raises_with_status(requests.codes.forbidden, - client.http_client_failure.get403) + await assert_raises_with_status(requests.codes.forbidden, client.http_client_failure.get403) + @pytest.mark.asyncio async def test_error_status_codes_404(client): - await assert_raises_with_status(requests.codes.not_found, - client.http_client_failure.put404) + await assert_raises_with_status(requests.codes.not_found, client.http_client_failure.put404) + @pytest.mark.asyncio async def test_error_status_codes_405(client): - await assert_raises_with_status(requests.codes.method_not_allowed, - client.http_client_failure.patch405) + await assert_raises_with_status(requests.codes.method_not_allowed, client.http_client_failure.patch405) + @pytest.mark.asyncio async def test_error_status_codes_406(client): - await assert_raises_with_status(requests.codes.not_acceptable, - client.http_client_failure.post406) + await assert_raises_with_status(requests.codes.not_acceptable, client.http_client_failure.post406) + @pytest.mark.asyncio async def test_error_status_codes_407(client): - await assert_raises_with_status(requests.codes.proxy_authentication_required, - client.http_client_failure.delete407) + await assert_raises_with_status(requests.codes.proxy_authentication_required, client.http_client_failure.delete407) + @pytest.mark.asyncio async def test_error_status_codes_409(client): - await assert_raises_with_status(requests.codes.conflict, - client.http_client_failure.put409) + await assert_raises_with_status(requests.codes.conflict, client.http_client_failure.put409) + @pytest.mark.asyncio async def test_error_status_codes_410(client): - await assert_raises_with_status(requests.codes.gone, - client.http_client_failure.head410) + await assert_raises_with_status(requests.codes.gone, client.http_client_failure.head410) + @pytest.mark.asyncio async def test_error_status_codes_411(client): - await assert_raises_with_status(requests.codes.length_required, - client.http_client_failure.get411) + await assert_raises_with_status(requests.codes.length_required, client.http_client_failure.get411) # TODO, 4042586: Support options operations in swagger modeler - #assert_raises_with_status(requests.codes.precondition_failed, + # assert_raises_with_status(requests.codes.precondition_failed, # await client.http_client_failure.options412) - await assert_raises_with_status(requests.codes.precondition_failed, - client.http_client_failure.get412) + await assert_raises_with_status(requests.codes.precondition_failed, client.http_client_failure.get412) + + await assert_raises_with_status(requests.codes.request_entity_too_large, client.http_client_failure.put413) - await assert_raises_with_status(requests.codes.request_entity_too_large, - client.http_client_failure.put413) + await assert_raises_with_status(requests.codes.request_uri_too_large, client.http_client_failure.patch414) - await assert_raises_with_status(requests.codes.request_uri_too_large, - client.http_client_failure.patch414) + await assert_raises_with_status(requests.codes.unsupported_media, client.http_client_failure.post415) - await assert_raises_with_status(requests.codes.unsupported_media, - client.http_client_failure.post415) + await assert_raises_with_status(requests.codes.requested_range_not_satisfiable, client.http_client_failure.get416) - await assert_raises_with_status(requests.codes.requested_range_not_satisfiable, - client.http_client_failure.get416) + await assert_raises_with_status(requests.codes.expectation_failed, client.http_client_failure.delete417) - await assert_raises_with_status(requests.codes.expectation_failed, - client.http_client_failure.delete417) + await assert_raises_with_status(429, client.http_client_failure.head429) - await assert_raises_with_status(429, - client.http_client_failure.head429) @pytest.mark.asyncio async def test_redirect_to_300(client): await assert_status(200, client.http_redirects.get300) await assert_status(200, client.http_redirects.head300) + @pytest.mark.asyncio async def test_redirect_to_301(client): await assert_status(200, client.http_redirects.head301) await assert_status(200, client.http_redirects.get301) await assert_status(requests.codes.moved_permanently, client.http_redirects.put301) + @pytest.mark.asyncio async def test_redirect_to_302(client): await assert_status(200, client.http_redirects.head302) await assert_status(200, client.http_redirects.get302) await assert_status(requests.codes.found, client.http_redirects.patch302) + @pytest.mark.asyncio async def test_redicret_to_303(client): await assert_status(200, client.http_redirects.post303) + @pytest.mark.asyncio async def test_redirect_to_307(client): await assert_status(200, client.http_redirects.head307) @@ -394,16 +394,19 @@ async def test_redirect_to_307(client): await assert_status(200, client.http_redirects.delete307) - @pytest.mark.asyncio async def test_bad_request_status_assert(client): - await assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.http_failure.get_empty_error) + await assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", client.http_failure.get_empty_error + ) + @pytest.mark.asyncio async def test_no_error_model_status_assert(client): - await assert_raises_with_status_and_response_contains(requests.codes.bad_request, "NoErrorModel", - client.http_failure.get_no_model_error) + await assert_raises_with_status_and_response_contains( + requests.codes.bad_request, "NoErrorModel", client.http_failure.get_no_model_error + ) + @pytest.mark.asyncio async def test_success_status_codes_200(client): @@ -415,13 +418,15 @@ async def test_success_status_codes_200(client): await client.http_success.delete200() # TODO, 4042586: Support options operations in swagger modeler - #assert await client.http_success.options200() + # assert await client.http_success.options200() + @pytest.mark.asyncio async def test_success_status_codes_201(client): await client.http_success.put201() await client.http_success.post201() + @pytest.mark.asyncio async def test_success_status_codes_202(client): await client.http_success.put202() @@ -429,6 +434,7 @@ async def test_success_status_codes_202(client): await client.http_success.patch202() await client.http_success.delete202() + @pytest.mark.asyncio async def test_success_status_codes_204(client): await client.http_success.head204() @@ -437,11 +443,12 @@ async def test_success_status_codes_204(client): await client.http_success.delete204() await client.http_success.patch204() + @pytest.mark.asyncio async def test_success_status_codes_404(client): await client.http_success.head404() + @pytest.mark.asyncio async def test_empty_no_content(client): - await assert_raises_with_status(requests.codes.bad_request, - client.http_failure.get_no_model_empty) + await assert_raises_with_status(requests.codes.bad_request, client.http_failure.get_no_model_empty) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_incorrect_error_response.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_incorrect_error_response.py index 2c76a299317..b1b8e8b62ec 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_incorrect_error_response.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_incorrect_error_response.py @@ -27,9 +27,10 @@ from azure.core.exceptions import HttpResponseError from incorrecterrorresponseversiontolerant.aio import IncorrectReturnedErrorModel + @pytest.mark.skip(reason="Not deserializing models yet") @pytest.mark.asyncio async def test_swallow_deserialization_error_for_error_model(): client = IncorrectReturnedErrorModel() with pytest.raises(HttpResponseError): - await client.get_incorrect_error_from_server() \ No newline at end of file + await client.get_incorrect_error_from_server() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_inputs.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_inputs.py index 048cb779276..ece15f7ba8f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_inputs.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_inputs.py @@ -26,14 +26,17 @@ import pytest from bodycomplexversiontolerant.aio import AutoRestComplexTestService from azure.core.pipeline.policies import CustomHookPolicy + try: from urlparse import urlparse # type: ignore except ImportError: from urllib.parse import urlparse + def get_client(callback): return AutoRestComplexTestService(policies=[CustomHookPolicy(raw_request_hook=callback)]) + @pytest.mark.asyncio async def test_header_input(): def get_headers(pipeline_request): @@ -41,29 +44,34 @@ def get_headers(pipeline_request): assert pipeline_request.http_request.headers["hello"] == "world!" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: await client.basic.get_empty(headers={"hello": "world!"}) assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_header_input_override(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 1 assert pipeline_request.http_request.headers["Accept"] == "my/content-type" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: await client.basic.get_empty(headers={"Accept": "my/content-type"}) assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_header_none_input(): async with AutoRestComplexTestService() as client: await client.basic.get_empty(headers=None) + @pytest.mark.asyncio async def test_header_case_insensitive(): def get_headers(pipeline_request): @@ -79,6 +87,7 @@ def get_headers(pipeline_request): assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_header_kwarg_and_header(): def get_headers(pipeline_request): @@ -86,23 +95,27 @@ def get_headers(pipeline_request): assert pipeline_request.http_request.headers["content-type"] == "my/json" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: await client.basic.put_valid(None, headers={"content-type": "shouldn't/be-me"}, content_type="my/json") assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_input(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "foo=bar" raise ValueError("Passed!") + client = get_client(callback=get_query) with pytest.raises(ValueError) as ex: await client.basic.get_empty(params={"foo": "bar"}) assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_input_override(): def get_query(pipeline_request): @@ -118,11 +131,13 @@ def get_query(pipeline_request): assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_none_input(): async with AutoRestComplexTestService() as client: await client.basic.get_empty(params=None) + @pytest.mark.asyncio async def test_query_case_insensitive(): def get_query(pipeline_request): @@ -137,6 +152,7 @@ def get_query(pipeline_request): assert str(ex.value) == "Passed!" await client.close() + @pytest.mark.asyncio async def test_query_kwarg_and_header(): def get_query(pipeline_request): diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_integer.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_integer.py index e782f9c7b23..774465dd6f5 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_integer.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_integer.py @@ -32,22 +32,26 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestIntegerTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_max_min_32_bit(client): - await client.int_operations.put_max32(2147483647) # sys.maxint + await client.int_operations.put_max32(2147483647) # sys.maxint await client.int_operations.put_min32(-2147483648) + @pytest.mark.asyncio async def test_max_min_64_bit(client): await client.int_operations.put_max64(9223372036854776000) # sys.maxsize await client.int_operations.put_min64(-9223372036854776000) + @pytest.mark.asyncio async def test_get_null_and_invalid(client): await client.int_operations.get_null() @@ -55,23 +59,27 @@ async def test_get_null_and_invalid(client): with pytest.raises(DecodeError): await client.int_operations.get_invalid() + @pytest.mark.asyncio async def test_get_overflow(client): # Testserver excepts these to fail, but they won't in Python and it's ok. await client.int_operations.get_overflow_int32() await client.int_operations.get_overflow_int64() + @pytest.mark.asyncio async def test_get_underflow(client): await client.int_operations.get_underflow_int32() await client.int_operations.get_underflow_int64() + @pytest.mark.asyncio async def test_unix_time_date(client): unix_date = datetime(year=2016, month=4, day=13) await client.int_operations.put_unix_time_date(serialize_unix(unix_date)) assert unix_date.utctimetuple() == deserialize_unix(await client.int_operations.get_unix_time()).utctimetuple() + @pytest.mark.asyncio async def test_get_null_and_invalid_unix_time(client): assert await client.int_operations.get_null_unix_time() is None diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_media_types.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_media_types.py index 889506b95cb..dd75bae7127 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_media_types.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_media_types.py @@ -30,12 +30,14 @@ import pytest import json + @pytest.fixture @async_generator async def client(): async with MediaTypesClient() as client: await yield_(client) + @pytest.mark.asyncio async def test_pdf(client): result = await client.analyze_body(input=b"PDF", content_type="application/pdf") @@ -43,37 +45,43 @@ async def test_pdf(client): with pytest.raises(TypeError): await client.analyze_body(input=b"PDF") + @pytest.mark.asyncio async def test_json(client): json_input = json.loads('{"source":"foo"}') result = await client.analyze_body(input=json_input) assert result == "Nice job with JSON" + @pytest.mark.asyncio async def test_content_type_with_encoding(client): - result = await client.content_type_with_encoding(input="hello", content_type='text/plain; charset=UTF-8') + result = await client.content_type_with_encoding(input="hello", content_type="text/plain; charset=UTF-8") assert result == "Nice job sending content type with encoding" + @pytest.mark.asyncio async def test_pdf_no_accept_header(client): await client.analyze_body_no_accept_header(input=b"PDF", content_type="application/pdf") + @pytest.mark.asyncio async def test_json_no_accept_header(client): json_input = json.loads('{"source":"foo"}') await client.analyze_body_no_accept_header(input=json_input) + @pytest.mark.asyncio async def test_binary_body_two_content_types(client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} await client.binary_body_with_two_content_types(json.dumps(json_input), content_type="application/json") content = b"hello, world" await client.binary_body_with_two_content_types(content, content_type="application/octet-stream") + @pytest.mark.asyncio async def test_binary_body_three_content_types(client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} await client.binary_body_with_three_content_types(json.dumps(json_input), content_type="application/json") content = b"hello, world" @@ -82,9 +90,10 @@ async def test_binary_body_three_content_types(client): content = "hello, world" await client.binary_body_with_three_content_types(content, content_type="text/plain") + @pytest.mark.asyncio async def test_body_three_types(client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} await client.body_three_types(json_input) content = b"hello, world" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_merge_patch_json.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_merge_patch_json.py index 3ae55ccd2c3..49faada049e 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_merge_patch_json.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_merge_patch_json.py @@ -27,11 +27,13 @@ import pytest + @pytest.fixture async def client(): async with MergePatchJsonClient() as client: yield client + @pytest.mark.asyncio async def test_merge_patch_json(client): await client.patch_single({"foo": "bar"}) == "Success!" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_model_flattening.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_model_flattening.py index aa8bff999b2..03fb167e0a1 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_model_flattening.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_model_flattening.py @@ -28,201 +28,156 @@ from modelflatteningversiontolerant.aio import AutoRestResourceFlatteningTestService import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestResourceFlatteningTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_flattening_array(client): - #Array + # Array result = await client.get_array() - assert 3 == len(result) + assert 3 == len(result) # Resource 1 - assert "1" == result[0]['id'] - assert "OK" == result[0]['properties']['provisioningStateValues'] - assert "Product1" == result[0]['properties']['p.name'] - assert "Flat" == result[0]['properties']['type'] - assert "Building 44" == result[0]['location'] - assert "Resource1" == result[0]['name'] - assert "Succeeded" == result[0]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result[0]['type'] - assert "value1" == result[0]['tags']["tag1"] - assert "value3" == result[0]['tags']["tag2"] + assert "1" == result[0]["id"] + assert "OK" == result[0]["properties"]["provisioningStateValues"] + assert "Product1" == result[0]["properties"]["p.name"] + assert "Flat" == result[0]["properties"]["type"] + assert "Building 44" == result[0]["location"] + assert "Resource1" == result[0]["name"] + assert "Succeeded" == result[0]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result[0]["type"] + assert "value1" == result[0]["tags"]["tag1"] + assert "value3" == result[0]["tags"]["tag2"] # Resource 2 - assert "2" == result[1]['id'] - assert "Resource2" == result[1]['name'] - assert "Building 44" == result[1]['location'] + assert "2" == result[1]["id"] + assert "Resource2" == result[1]["name"] + assert "Building 44" == result[1]["location"] # Resource 3 - assert "3" == result[2]['id'] - assert "Resource3" == result[2]['name'] + assert "3" == result[2]["id"] + assert "Resource3" == result[2]["name"] resource_array = [ - { - 'tags': { - 'tag1': 'value1', - 'tag2': 'value3' - }, - 'location': 'West US' - }, - { - 'location': 'Building 44' - } + {"tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US"}, + {"location": "Building 44"}, ] await client.put_array(resource_array) + @pytest.mark.asyncio async def test_flattening_dictionary(client): - #Dictionary + # Dictionary result = await client.get_dictionary() - assert 3 == len(result) + assert 3 == len(result) # Resource 1 - assert "1" == result["Product1"]['id'] - assert "OK" == result["Product1"]['properties']['provisioningStateValues'] - assert "Product1" == result["Product1"]['properties']['p.name'] - assert "Flat" == result["Product1"]['properties']['type'] - assert "Building 44" == result["Product1"]['location'] - assert "Resource1" == result["Product1"]['name'] - assert "Succeeded" == result["Product1"]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result["Product1"]['type'] - assert "value1" == result["Product1"]['tags']["tag1"] - assert "value3" == result["Product1"]['tags']["tag2"] + assert "1" == result["Product1"]["id"] + assert "OK" == result["Product1"]["properties"]["provisioningStateValues"] + assert "Product1" == result["Product1"]["properties"]["p.name"] + assert "Flat" == result["Product1"]["properties"]["type"] + assert "Building 44" == result["Product1"]["location"] + assert "Resource1" == result["Product1"]["name"] + assert "Succeeded" == result["Product1"]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result["Product1"]["type"] + assert "value1" == result["Product1"]["tags"]["tag1"] + assert "value3" == result["Product1"]["tags"]["tag2"] # Resource 2 - assert "2" == result["Product2"]['id'] - assert "Resource2" == result["Product2"]['name'] - assert "Building 44" == result["Product2"]['location'] + assert "2" == result["Product2"]["id"] + assert "Resource2" == result["Product2"]["name"] + assert "Building 44" == result["Product2"]["location"] # Resource 3 - assert "3" == result["Product3"]['id'] - assert "Resource3" == result["Product3"]['name'] + assert "3" == result["Product3"]["id"] + assert "Resource3" == result["Product3"]["name"] resource_dictionary = { "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, + "tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } + "properties": {"p.name": "Product1", "type": "Flat"}, }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } + "Resource2": {"location": "Building 44", "properties": {"p.name": "Product2", "type": "Flat"}}, } await client.put_dictionary(resource_dictionary) + @pytest.mark.asyncio async def test_flattening_complex_object(client): - #ResourceCollection + # ResourceCollection result = await client.get_resource_collection() - #dictionaryofresources - assert 3 == len(result['dictionaryofresources']) + # dictionaryofresources + assert 3 == len(result["dictionaryofresources"]) # Resource 1 - assert "1" == result['dictionaryofresources']["Product1"]['id'] - assert "OK" == result['dictionaryofresources']["Product1"]['properties']['provisioningStateValues'] - assert "Product1" == result['dictionaryofresources']["Product1"]['properties']['p.name'] - assert "Flat" == result['dictionaryofresources']["Product1"]['properties']['type'] - assert "Building 44" == result['dictionaryofresources']["Product1"]['location'] - assert "Resource1" == result['dictionaryofresources']["Product1"]['name'] - assert "Succeeded" == result['dictionaryofresources']["Product1"]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result['dictionaryofresources']["Product1"]['type'] - assert "value1" == result['dictionaryofresources']["Product1"]['tags']["tag1"] - assert "value3" == result['dictionaryofresources']["Product1"]['tags']["tag2"] + assert "1" == result["dictionaryofresources"]["Product1"]["id"] + assert "OK" == result["dictionaryofresources"]["Product1"]["properties"]["provisioningStateValues"] + assert "Product1" == result["dictionaryofresources"]["Product1"]["properties"]["p.name"] + assert "Flat" == result["dictionaryofresources"]["Product1"]["properties"]["type"] + assert "Building 44" == result["dictionaryofresources"]["Product1"]["location"] + assert "Resource1" == result["dictionaryofresources"]["Product1"]["name"] + assert "Succeeded" == result["dictionaryofresources"]["Product1"]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result["dictionaryofresources"]["Product1"]["type"] + assert "value1" == result["dictionaryofresources"]["Product1"]["tags"]["tag1"] + assert "value3" == result["dictionaryofresources"]["Product1"]["tags"]["tag2"] # Resource 2 - assert "2" == result['dictionaryofresources']["Product2"]['id'] - assert "Resource2" == result['dictionaryofresources']["Product2"]['name'] - assert "Building 44" == result['dictionaryofresources']["Product2"]['location'] + assert "2" == result["dictionaryofresources"]["Product2"]["id"] + assert "Resource2" == result["dictionaryofresources"]["Product2"]["name"] + assert "Building 44" == result["dictionaryofresources"]["Product2"]["location"] # Resource 3 - assert "3" == result['dictionaryofresources']["Product3"]['id'] - assert "Resource3" == result['dictionaryofresources']["Product3"]['name'] + assert "3" == result["dictionaryofresources"]["Product3"]["id"] + assert "Resource3" == result["dictionaryofresources"]["Product3"]["name"] - #arrayofresources - assert 3 == len(result['arrayofresources']) + # arrayofresources + assert 3 == len(result["arrayofresources"]) # Resource 1 - assert "4" == result['arrayofresources'][0]['id'] - assert "OK" == result['arrayofresources'][0]['properties']['provisioningStateValues'] - assert "Product4" == result['arrayofresources'][0]['properties']['p.name'] - assert "Flat" == result['arrayofresources'][0]['properties']['type'] - assert "Building 44" == result['arrayofresources'][0]['location'] - assert "Resource4" == result['arrayofresources'][0]['name'] - assert "Succeeded" == result['arrayofresources'][0]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result['arrayofresources'][0]['type'] - assert "value1" == result['arrayofresources'][0]['tags']["tag1"] - assert "value3" == result['arrayofresources'][0]['tags']["tag2"] + assert "4" == result["arrayofresources"][0]["id"] + assert "OK" == result["arrayofresources"][0]["properties"]["provisioningStateValues"] + assert "Product4" == result["arrayofresources"][0]["properties"]["p.name"] + assert "Flat" == result["arrayofresources"][0]["properties"]["type"] + assert "Building 44" == result["arrayofresources"][0]["location"] + assert "Resource4" == result["arrayofresources"][0]["name"] + assert "Succeeded" == result["arrayofresources"][0]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result["arrayofresources"][0]["type"] + assert "value1" == result["arrayofresources"][0]["tags"]["tag1"] + assert "value3" == result["arrayofresources"][0]["tags"]["tag2"] # Resource 2 - assert "5" == result['arrayofresources'][1]['id'] - assert "Resource5" == result['arrayofresources'][1]['name'] - assert "Building 44" == result['arrayofresources'][1]['location'] + assert "5" == result["arrayofresources"][1]["id"] + assert "Resource5" == result["arrayofresources"][1]["name"] + assert "Building 44" == result["arrayofresources"][1]["location"] # Resource 3 - assert "6" == result['arrayofresources'][2]['id'] - assert "Resource6" == result['arrayofresources'][2]['name'] + assert "6" == result["arrayofresources"][2]["id"] + assert "Resource6" == result["arrayofresources"][2]["name"] - #productresource - assert "7" == result['productresource']['id'] - assert "Resource7" == result['productresource']['name'] + # productresource + assert "7" == result["productresource"]["id"] + assert "Resource7" == result["productresource"]["name"] resource_dictionary = { - "productresource": { - "location": "India", - "properties": { - "p.name": "Azure", - "type": "Flat" - } - }, + "productresource": {"location": "India", "properties": {"p.name": "Azure", "type": "Flat"}}, "arrayofresources": [ { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, + "tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } + "properties": {"p.name": "Product1", "type": "Flat"}, }, - { - "location": "East US", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } + {"location": "East US", "properties": {"p.name": "Product2", "type": "Flat"}}, ], "dictionaryofresources": { "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, + "tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } + "properties": {"p.name": "Product1", "type": "Flat"}, }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - } + "Resource2": {"location": "Building 44", "properties": {"p.name": "Product2", "type": "Flat"}}, + }, } await client.put_resource_collection(resource_dictionary) + @pytest.mark.asyncio async def test_model_flattening_simple(client): @@ -232,14 +187,12 @@ async def test_model_flattening_simple(client): "details": { "max_product_display_name": "max name", "max_product_capacity": "Large", - "max_product_image": { - "generic_value": "https://generic", - "@odata.value": "http://foo" - } - } + "max_product_image": {"generic_value": "https://generic", "@odata.value": "http://foo"}, + }, } result = await client.put_simple_product(simple_product) - assert result == simple_product + assert result == simple_product + @pytest.mark.asyncio async def test_model_flattening_with_parameter_flattening(client): @@ -250,14 +203,13 @@ async def test_model_flattening_with_parameter_flattening(client): "details": { "max_product_display_name": "max name", "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } + "max_product_image": {"@odata.value": "http://foo"}, + }, } result = await client.post_flattened_simple_product(simple_product) assert result == simple_product + @pytest.mark.asyncio async def test_model_flattening_with_grouping(client): simple_product = { @@ -266,10 +218,8 @@ async def test_model_flattening_with_grouping(client): "details": { "max_product_display_name": "max name", "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } + "max_product_image": {"@odata.value": "http://foo"}, + }, } - result = await client.put_simple_product_with_grouping('groupproduct', simple_product) + result = await client.put_simple_product_with_grouping("groupproduct", simple_product) assert result == simple_product diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_multiple_inheritance.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_multiple_inheritance.py index a5a53d6d3a3..1405c1cbca0 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_multiple_inheritance.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_multiple_inheritance.py @@ -29,53 +29,72 @@ from multipleinheritanceversiontolerant.aio import MultipleInheritanceServiceClient import pytest + @pytest.fixture @async_generator async def client(): async with MultipleInheritanceServiceClient() as client: await yield_(client) + @pytest.mark.asyncio async def test_get_pet(client): assert {"name": "Peanut"} == await client.get_pet() + @pytest.mark.asyncio async def test_put_pet(client): result = await client.put_pet({"name": "Butter"}) assert result == "Pet was correct!" + @pytest.mark.asyncio async def test_get_horse(client): assert {"name": "Fred", "isAShowHorse": True} == await client.get_horse() + @pytest.mark.asyncio async def test_put_horse(client): result = await client.put_horse({"name": "General", "isAShowHorse": False}) assert result == "Horse was correct!" + @pytest.mark.asyncio async def test_get_feline(client): assert {"meows": True, "hisses": True} == await client.get_feline() + @pytest.mark.asyncio async def test_put_feline(client): result = await client.put_feline({"meows": False, "hisses": True}) assert result == "Feline was correct!" + @pytest.mark.asyncio async def test_get_cat(client): assert {"name": "Whiskers", "likesMilk": True, "meows": True, "hisses": True} == await client.get_cat() + @pytest.mark.asyncio async def test_put_cat(client): result = await client.put_cat({"name": "Boots", "likesMilk": False, "meows": True, "hisses": False}) assert result == "Cat was correct!" + @pytest.mark.asyncio async def test_get_kitten(client): - assert {"name": "Gatito", "likesMilk": True, "meows": True, "hisses": True, "eatsMiceYet": False} == await client.get_kitten() + assert { + "name": "Gatito", + "likesMilk": True, + "meows": True, + "hisses": True, + "eatsMiceYet": False, + } == await client.get_kitten() + @pytest.mark.asyncio async def test_put_kitten(client): - result = await client.put_kitten({"name": "Kitty", "likesMilk": False, "meows": True, "hisses": False, "eatsMiceYet": True}) - assert result == "Kitten was correct!" \ No newline at end of file + result = await client.put_kitten( + {"name": "Kitty", "likesMilk": False, "meows": True, "hisses": False, "eatsMiceYet": True} + ) + assert result == "Kitten was correct!" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_no_namespace_flag.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_no_namespace_flag.py index 1806f2e7c4a..6f1926971b1 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_no_namespace_flag.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_no_namespace_flag.py @@ -26,12 +26,14 @@ import pytest from anything_client.aio import AnythingClient + @pytest.fixture async def client(): async with AnythingClient() as client: yield client + @pytest.mark.asyncio async def test_call(client): # make sure we can do a call with an sdk with no namespace flag - assert await client.get_string() == 'anything' + assert await client.get_string() == "anything" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_non_string_enums.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_non_string_enums.py index e9b259e1fd6..07b8f35f6d8 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_non_string_enums.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_non_string_enums.py @@ -28,27 +28,32 @@ import pytest + @pytest.fixture @async_generator async def client(): async with NonStringEnumsClient() as client: await yield_(client) + @pytest.mark.asyncio async def test_put_int_enum(client): result = await client.int_operations.put(200) assert result == "Nice job posting an int enum" + @pytest.mark.asyncio async def test_get_int_enum(client): result = await client.int_operations.get() assert result == 429 + @pytest.mark.asyncio async def test_put_float_enum(client): result = await client.float.put(200.4) assert result == "Nice job posting a float enum" + @pytest.mark.asyncio async def test_get_float_enum(client): result = await client.float.get() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_number.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_number.py index 8b6fc6f1ebd..e57af66cbe8 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_number.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_number.py @@ -32,76 +32,91 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestNumberTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_big_float(client): - await client.number.put_big_float(3.402823e+20) - assert (await client.number.get_big_float()) == 3.402823e+20 + await client.number.put_big_float(3.402823e20) + assert (await client.number.get_big_float()) == 3.402823e20 + @pytest.mark.asyncio async def test_small_float(client): await client.number.put_small_float(3.402823e-20) - assert (await client.number.get_small_float()) == 3.402823e-20 + assert (await client.number.get_small_float()) == 3.402823e-20 + @pytest.mark.asyncio async def test_big_double(client): - await client.number.put_big_double(2.5976931e+101) - assert (await client.number.get_big_double()) == 2.5976931e+101 + await client.number.put_big_double(2.5976931e101) + assert (await client.number.get_big_double()) == 2.5976931e101 + @pytest.mark.asyncio async def test_small_double(client): await client.number.put_small_double(2.5976931e-101) - assert (await client.number.get_small_double()) == 2.5976931e-101 + assert (await client.number.get_small_double()) == 2.5976931e-101 + @pytest.mark.asyncio async def test_big_double_negative_decimal(client): await client.number.put_big_double_negative_decimal() - assert (await client.number.get_big_double_negative_decimal()) == -99999999.99 + assert (await client.number.get_big_double_negative_decimal()) == -99999999.99 + @pytest.mark.asyncio async def test_big_double_positive_decimal(client): await client.number.put_big_double_positive_decimal() - assert (await client.number.get_big_double_positive_decimal()) == 99999999.99 + assert (await client.number.get_big_double_positive_decimal()) == 99999999.99 + @pytest.mark.asyncio async def test_big_decimal(client): - await client.number.put_big_decimal(2.5976931e+101) - assert (await client.number.get_big_decimal()) == 2.5976931e+101 + await client.number.put_big_decimal(2.5976931e101) + assert (await client.number.get_big_decimal()) == 2.5976931e101 + @pytest.mark.asyncio async def test_small_decimal(client): await client.number.put_small_decimal(2.5976931e-101) - assert (await client.number.get_small_decimal()) == 2.5976931e-101 + assert (await client.number.get_small_decimal()) == 2.5976931e-101 + @pytest.mark.asyncio async def test_get_big_decimal_negative_decimal(client): await client.number.put_big_decimal_positive_decimal() - assert (await client.number.get_big_decimal_negative_decimal()) == -99999999.99 + assert (await client.number.get_big_decimal_negative_decimal()) == -99999999.99 + @pytest.mark.asyncio async def test_get_big_decimal_positive_decimal(client): await client.number.put_big_decimal_negative_decimal() - assert (await client.number.get_big_decimal_positive_decimal()) == 99999999.99 + assert (await client.number.get_big_decimal_positive_decimal()) == 99999999.99 + @pytest.mark.asyncio async def test_get_null(client): await client.number.get_null() + @pytest.mark.asyncio async def test_get_invalid_decimal(client): with pytest.raises(DecodeError): await client.number.get_invalid_decimal() + @pytest.mark.asyncio async def test_get_invalid_double(client): with pytest.raises(DecodeError): await client.number.get_invalid_double() + @pytest.mark.asyncio async def test_get_invalid_float(client): with pytest.raises(DecodeError): diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_object_type.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_object_type.py index ff71cfd1bdb..8c82a55015b 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_object_type.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_object_type.py @@ -29,23 +29,28 @@ import pytest + @pytest.fixture @async_generator async def client(): async with ObjectTypeClient() as client: await yield_(client) + + @pytest.mark.asyncio async def test_get_object(client): response = await client.get() assert response == {"message": "An object was successfully returned"} + @pytest.mark.asyncio async def test_put_object_success(client): response = await client.put({"foo": "bar"}) assert response is None + @pytest.mark.asyncio async def test_put_object_fail(client): with pytest.raises(HttpResponseError) as ex: await client.put({"should": "fail"}) - assert ex.value.response.json() == {"message": "The object you passed was incorrect"} \ No newline at end of file + assert ex.value.response.json() == {"message": "The object you passed was incorrect"} diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_parameterized_endpoint.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_parameterized_endpoint.py index 824979e2977..fa0b22e4589 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_parameterized_endpoint.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_parameterized_endpoint.py @@ -26,11 +26,13 @@ import pytest from parameterizedendpointversiontolerant.aio import ParmaterizedEndpointClient + @pytest.fixture async def client(): async with ParmaterizedEndpointClient(endpoint="http://localhost:3000") as client: yield client + @pytest.mark.asyncio async def test_get(client): await client.get() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_required_optional.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_required_optional.py index 41dab14e119..5547dbd160a 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_required_optional.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_required_optional.py @@ -32,28 +32,31 @@ import pytest + @pytest.fixture @async_generator async def client_required(): async with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - ) as client: + "required_path", + "required_query", + ) as client: client._config.required_global_path = "required_path" client._config.required_global_query = "required_query" await yield_(client) + @pytest.fixture @async_generator async def client(): async with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - ) as client: + "required_path", + "required_query", + ) as client: client._config.required_global_path = None client._config.required_global_query = None await yield_(client) + # These clients have a required global path and query @pytest.mark.asyncio async def test_put_optional(client_required): @@ -61,33 +64,41 @@ async def test_put_optional(client_required): await client_required.implicit.put_optional_body(None) await client_required.implicit.put_optional_header(query_parameter=None) + @pytest.mark.asyncio async def test_get_optional_global_query(client_required): await client_required.implicit.get_optional_global_query(cls=None) + @pytest.mark.asyncio async def test_post_optional_integer(client_required): await client_required.explicit.post_optional_integer_parameter(None) await client_required.explicit.post_optional_integer_property({"value": None}) await client_required.explicit.post_optional_integer_header(header_parameter=None) + @pytest.mark.asyncio async def test_post_optional_string(client_required): await client_required.explicit.post_optional_string_parameter(None) await client_required.explicit.post_optional_string_property({"value": None}) - await client_required.explicit.post_optional_string_header(body_parameter=None) # header param that's called bodyParameter. confusing, but c'est la vie + await client_required.explicit.post_optional_string_header( + body_parameter=None + ) # header param that's called bodyParameter. confusing, but c'est la vie + @pytest.mark.asyncio async def test_post_optional_class(client_required): await client_required.explicit.post_optional_class_parameter(None) await client_required.explicit.post_optional_class_property({"value": None}) + @pytest.mark.asyncio async def test_post_optional_array(client_required): await client_required.explicit.post_optional_array_parameter(None) await client_required.explicit.post_optional_array_property({"value": None}) await client_required.explicit.post_optional_array_header(header_parameter=None) + @pytest.mark.asyncio async def test_implicit_get_required(client): with pytest.raises(ValueError): @@ -99,6 +110,7 @@ async def test_implicit_get_required(client): with pytest.raises(ValueError): await client.implicit.get_required_global_query() + @pytest.mark.asyncio async def test_post_required_string(client): with pytest.raises(ValueError): @@ -112,6 +124,7 @@ async def test_post_required_string(client): await client.explicit.post_required_string_property(None) assert "Not Found" in str(ex.value) + @pytest.mark.asyncio async def test_post_required_array(client): with pytest.raises(TypeError): @@ -125,6 +138,7 @@ async def test_post_required_array(client): await client.explicit.post_required_array_property({"value": None}) assert "Not Found" in str(ex.value) + @pytest.mark.asyncio async def test_post_required_class(client): with pytest.raises(HttpResponseError) as ex: @@ -137,17 +151,20 @@ async def test_post_required_class(client): assert "Not Found" in str(ex.value) + @pytest.mark.asyncio async def test_explict_put_optional_binary_body(client): await client.explicit.put_optional_binary_body() + @pytest.mark.asyncio async def test_explict_put_required_binary_body(client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: await client.explicit.put_required_binary_body(stream_data) + @pytest.mark.asyncio async def test_implicit_put_optional_binary_body(client): await client.implicit.put_optional_binary_body() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_reserved_words.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_reserved_words.py index f1a11040b81..868d4ede54d 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_reserved_words.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_reserved_words.py @@ -26,38 +26,43 @@ import pytest from reservedwordsversiontolerant.aio import ReservedWordsClient + @pytest.fixture async def client(): async with ReservedWordsClient() as client: yield client + @pytest.mark.asyncio async def test_operation_group_import(client): await client.import_operations.operation_one(parameter1="foo") + @pytest.mark.asyncio async def test_operation_with_content_param(client): await client.operation_with_content_param(b"hello, world") + @pytest.mark.asyncio async def test_operation_with_json_param(client): await client.operation_with_json_param({"hello": "world"}) + @pytest.mark.asyncio async def test_operation_with_data_param(client): await client.operation_with_data_param({"data": "hello", "world": "world"}) + @pytest.mark.asyncio async def test_operation_with_files_param(client): - await client.operation_with_files_param(files = { - "file_name": "my.txt", - "files": b'bytes' - }) + await client.operation_with_files_param(files={"file_name": "my.txt", "files": b"bytes"}) + @pytest.mark.asyncio async def test_operation_with_url(client): await client.operation_with_url("foo", header_parameters="x-ms-header", query_parameters=["one", "two"]) + @pytest.mark.asyncio async def test_operation_with_enum(client: ReservedWordsClient): await client.reserved_enum(enum_parameter="import") diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_security.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_security.py index e0b8d7ae58a..376e934cad8 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_security.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_security.py @@ -30,15 +30,17 @@ from azure.core.pipeline.policies import AzureKeyCredentialPolicy from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy + @pytest.mark.asyncio async def test_security_aad_swagger(credential_async): client = AutorestSecurityAad(credential=credential_async) assert isinstance(client._config.authentication_policy, AsyncBearerTokenCredentialPolicy) await client.head(enforce_https=False) + @pytest.mark.asyncio async def test_security_key_swagger(): # the key value shall keep same with https://github.com/Azure/autorest.testserver/tree/main/src/test-routes/security.ts - client = AutorestSecurityKey(credential=AzureKeyCredential('123456789')) + client = AutorestSecurityKey(credential=AzureKeyCredential("123456789")) assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) await client.head() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_send_request.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_send_request.py index 5167f064a1a..21c14ec97bf 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_send_request.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_send_request.py @@ -33,26 +33,28 @@ cwd = dirname(realpath(__file__)) + @pytest.mark.asyncio async def test_send_request_with_body_get_model_deserialize(): - from bodycomplexversiontolerant.aio import AutoRestComplexTestService\ + from bodycomplexversiontolerant.aio import AutoRestComplexTestService client = AutoRestComplexTestService() - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = await client.send_request(request) response.raise_for_status() deserialized = response.json() - assert 2 == deserialized['id'] - assert "Siameeee" == deserialized['name'] - assert -1 == deserialized['hates'][1]['id'] - assert "Tomato" == deserialized['hates'][1]['name'] + assert 2 == deserialized["id"] + assert "Siameeee" == deserialized["name"] + assert -1 == deserialized["hates"][1]["id"] + assert "Tomato" == deserialized["hates"][1]["name"] + @pytest.mark.asyncio async def test_send_request_with_stream_get_direct_json(): @@ -60,20 +62,21 @@ async def test_send_request_with_stream_get_direct_json(): client = AutoRestComplexTestService() - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = await client.send_request(request, stream=True) - data = b''.join([chunk async for chunk in response.iter_bytes()]).decode('utf-8') + data = b"".join([chunk async for chunk in response.iter_bytes()]).decode("utf-8") json_response = json.loads(data) - assert 2 == json_response['id'] - assert "Siameeee" == json_response['name'] - assert - 1 == json_response['hates'][1]['id'] - assert "Tomato" == json_response['hates'][1]['name'] + assert 2 == json_response["id"] + assert "Siameeee" == json_response["name"] + assert -1 == json_response["hates"][1]["id"] + assert "Tomato" == json_response["hates"][1]["name"] + @pytest.mark.asyncio async def test_send_request_with_body_put_json_dumps(): @@ -85,32 +88,21 @@ async def test_send_request_with_body_put_json_dumps(): "id": 2, "name": "Siameeee", "color": "green", - "hates": - [ - { - "id": 1, - "name": "Potato", - "food": "tomato" - }, - { - "id": -1, - "name": "Tomato", - "food": "french fries" - } - ], - "breed": "persian" + "hates": [{"id": 1, "name": "Potato", "food": "tomato"}, {"id": -1, "name": "Tomato", "food": "french fries"}], + "breed": "persian", } - request = HttpRequest("PUT", "/complex/inheritance/valid", - headers={ - 'Content-Type': 'application/json' - }, + request = HttpRequest( + "PUT", + "/complex/inheritance/valid", + headers={"Content-Type": "application/json"}, json=siamese_body, ) response = await client.send_request(request) assert response.status_code == 200 + @pytest.mark.asyncio async def test_send_request_get_stream(): from bodyfileversiontolerant.aio import AutoRestSwaggerBATFileService @@ -119,10 +111,10 @@ async def test_send_request_get_stream(): file_length = 0 with io.BytesIO() as file_handle: - request = HttpRequest("GET", "/files/stream/nonempty", - headers={ - 'Accept': 'image/png, application/json' - }, + request = HttpRequest( + "GET", + "/files/stream/nonempty", + headers={"Accept": "image/png, application/json"}, ) response = await client.send_request(request, stream=True) @@ -135,16 +127,29 @@ async def test_send_request_get_stream(): file_length += len(data) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) + join( + cwd, + pardir, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) - with open(sample_file, 'rb') as data: + with open(sample_file, "rb") as data: sample_data = hash(data.read()) assert sample_data == hash(file_handle.getvalue()) + @pytest.mark.asyncio async def test_send_request_put_stream(): from bodyformdataversiontolerant.aio import AutoRestSwaggerBATFormDataService @@ -152,33 +157,34 @@ async def test_send_request_put_stream(): client = AutoRestSwaggerBATFormDataService() test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: - request = HttpRequest("PUT", '/formdata/stream/uploadfile', - headers={ - 'Content-Type': 'application/octet-stream' - }, + request = HttpRequest( + "PUT", + "/formdata/stream/uploadfile", + headers={"Content-Type": "application/octet-stream"}, data=stream_data, ) response = await client.send_request(request, stream=True) assert response.status_code == 200 + @pytest.mark.asyncio async def test_send_request_full_url(): from bodycomplexversiontolerant.aio import AutoRestComplexTestService client = AutoRestComplexTestService(endpoint="http://fakeUrl") - request = HttpRequest("GET", "http://localhost:3000/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, - ) + request = HttpRequest( + "GET", + "http://localhost:3000/complex/inheritance/valid", + headers={"Accept": "application/json"}, + ) response = await client.send_request(request) response.raise_for_status() deserialized = response.json() - assert 2 == deserialized['id'] - assert "Siameeee" == deserialized['name'] - assert -1 == deserialized['hates'][1]['id'] - assert "Tomato" == deserialized['hates'][1]['name'] + assert 2 == deserialized["id"] + assert "Siameeee" == deserialized["name"] + assert -1 == deserialized["hates"][1]["id"] + assert "Tomato" == deserialized["hates"][1]["name"] diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_string_tests.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_string_tests.py index 7fed19eff10..f6c2558f6f7 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_string_tests.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_string_tests.py @@ -31,23 +31,27 @@ from ..serializer import deserialize_base64, serialize_base64 import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestSwaggerBATService() as client: await yield_(client) + @pytest.mark.asyncio async def test_null(client): assert await client.string.get_null() is None await client.string.put_null() + @pytest.mark.asyncio async def test_empty(client): - assert "" == await client.string.get_empty() + assert "" == await client.string.get_empty() # changing this behavior because of this pr being merged: https://github.com/Azure/autorest.testserver/pull/145/files await client.string.put_empty() + @pytest.mark.asyncio async def test_mbcs(client): try: @@ -65,7 +69,8 @@ async def test_mbcs(client): "\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" "\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" "\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") except AttributeError: test_str = ( @@ -82,51 +87,68 @@ async def test_mbcs(client): b"\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" b"\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" b"\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") assert test_str == await client.string.get_mbcs() await client.string.put_mbcs() + @pytest.mark.asyncio async def test_whitespace(client): test_str = " Now is the time for all good men to come to the aid of their country " - assert test_str == await client.string.get_whitespace() + assert test_str == await client.string.get_whitespace() await client.string.put_whitespace() + @pytest.mark.asyncio async def test_get_not_provided(client): assert await client.string.get_not_provided() is None + @pytest.mark.asyncio async def test_enum_not_expandable(client): - assert 'red color' == await client.enum.get_not_expandable() - await client.enum.put_not_expandable('red color') + assert "red color" == await client.enum.get_not_expandable() + await client.enum.put_not_expandable("red color") # Autorest v3 is switching behavior here. Old Autorest would have thrown a serialization error, # but now we allow the user to pass strings as enums, so the raised exception is different. with pytest.raises(HttpResponseError): - await client.enum.put_not_expandable('not a colour') + await client.enum.put_not_expandable("not a colour") + @pytest.mark.asyncio async def test_get_base64_encoded(client): - assert deserialize_base64(await client.string.get_base64_encoded()) == 'a string that gets encoded with base64'.encode() + assert ( + deserialize_base64(await client.string.get_base64_encoded()) + == "a string that gets encoded with base64".encode() + ) + @pytest.mark.asyncio async def test_base64_url_encoded(client): - assert deserialize_base64(await client.string.get_base64_url_encoded()) == 'a string that gets encoded with base64url'.encode() - await client.string.put_base64_url_encoded(serialize_base64('a string that gets encoded with base64url'.encode())) + assert ( + deserialize_base64(await client.string.get_base64_url_encoded()) + == "a string that gets encoded with base64url".encode() + ) + await client.string.put_base64_url_encoded(serialize_base64("a string that gets encoded with base64url".encode())) + @pytest.mark.asyncio async def test_get_null_base64_url_encoded(client): assert await client.string.get_null_base64_url_encoded() is None + @pytest.mark.asyncio async def test_enum_referenced(client): - await client.enum.put_referenced('red color') + await client.enum.put_referenced("red color") + + assert await client.enum.get_referenced() == "red color" - assert await client.enum.get_referenced() == 'red color' @pytest.mark.asyncio async def test_enum_referenced_constant(client): await client.enum.put_referenced_constant({"ColorConstant": "green-color"}) - assert await client.enum.get_referenced_constant() == {'field1': 'Sample String'} # there's no constant on the response, so just getting field1 + assert await client.enum.get_referenced_constant() == { + "field1": "Sample String" + } # there's no constant on the response, so just getting field1 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_time.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_time.py index 096bb6285f0..4d438bae7f7 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_time.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_time.py @@ -32,16 +32,19 @@ import pytest from ..serializer import serialize_time, deserialize_time + @pytest.fixture @async_generator async def client(): async with AutoRestTimeTestService() as client: await yield_(client) + @pytest.mark.asyncio async def test_get(client): assert deserialize_time(await client.time.get()) == datetime.time(11, 34, 56) + @pytest.mark.asyncio async def test_put(client): result = await client.time.put(serialize_time(datetime.time(8, 7, 56))) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_tracing.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_tracing.py index 05ec0d8630d..7c3025dc0d9 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_tracing.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_tracing.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -38,4 +37,4 @@ def has_tracing_decorator(function): def test_url(): client = AutoRestUrlTestService("", endpoint="dummy url") - assert has_tracing_decorator(client.paths.get_boolean_false) \ No newline at end of file + assert has_tracing_decorator(client.paths.get_boolean_false) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_url.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_url.py index e73e9cc2fc8..4ed849bf9a1 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_url.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_url.py @@ -31,22 +31,26 @@ import pytest + @pytest.fixture @async_generator async def client(): - async with AutoRestUrlTestService('') as client: + async with AutoRestUrlTestService("") as client: await yield_(client) + @pytest.fixture @async_generator async def multi_client(): async with AutoRestUrlMutliCollectionFormatTestService() as client: await yield_(client) + @pytest.fixture def test_array_query(): return ["ArrayQuery1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + @pytest.mark.asyncio async def test_byte_empty_and_null(client): await client.paths.byte_empty() @@ -54,58 +58,70 @@ async def test_byte_empty_and_null(client): with pytest.raises(ValueError): await client.paths.byte_null(None) + @pytest.mark.asyncio async def test_byte_multi_byte(client): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") await client.paths.byte_multi_byte(u_bytes) + @pytest.mark.asyncio async def test_date_null(client): with pytest.raises(ValueError): await client.paths.date_null(None) + @pytest.mark.asyncio async def test_date_time_null(client): with pytest.raises(ValueError): await client.paths.date_time_null(None) + @pytest.mark.asyncio async def test_date_time_valid(client): await client.paths.date_time_valid() + @pytest.mark.asyncio async def test_date_valid(client): await client.paths.date_valid() + @pytest.mark.asyncio async def test_unix_time_url(client): await client.paths.unix_time_url(datetime(year=2016, month=4, day=13)) + @pytest.mark.asyncio async def test_double_decimal(client): await client.paths.double_decimal_negative() await client.paths.double_decimal_positive() + @pytest.mark.asyncio async def test_float_scientific(client): await client.paths.float_scientific_negative() await client.paths.float_scientific_positive() + @pytest.mark.asyncio async def test_get_boolean(client): await client.paths.get_boolean_false() await client.paths.get_boolean_true() + @pytest.mark.asyncio async def test_int(client): await client.paths.get_int_negative_one_million() await client.paths.get_int_one_million() + @pytest.mark.asyncio async def test_get_long(client): await client.paths.get_negative_ten_billion() await client.paths.get_ten_billion() + @pytest.mark.asyncio async def test_string_empty_and_null(client): await client.paths.string_empty() @@ -113,123 +129,147 @@ async def test_string_empty_and_null(client): with pytest.raises(ValueError): await client.paths.string_null(None) + @pytest.mark.asyncio async def test_array_csv_in_path(client): test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] await client.paths.array_csv_in_path(test_array) + @pytest.mark.asyncio async def test_string_url_encoded(client): await client.paths.string_url_encoded() + @pytest.mark.asyncio async def test_paths_unicode(client): await client.paths.string_unicode() + @pytest.mark.asyncio async def test_string_url_non_encoded(client): await client.paths.string_url_non_encoded() + @pytest.mark.asyncio async def test_enum_valid(client): await client.paths.enum_valid("green color") + @pytest.mark.asyncio async def test_enum_null(client): with pytest.raises(ValueError): await client.paths.enum_null(None) + @pytest.mark.asyncio async def test_base64_url(client): await client.paths.base64_url("lorem".encode()) + @pytest.mark.asyncio async def test_queries_byte(client): await client.queries.byte_empty() - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") await client.queries.byte_multi_byte(byte_query=u_bytes) await client.queries.byte_null() + @pytest.mark.asyncio async def test_queries_date(client): await client.queries.date_null() await client.queries.date_valid() + @pytest.mark.asyncio async def test_queries_date_time(client): await client.queries.date_time_null() await client.queries.date_time_valid() + @pytest.mark.asyncio async def test_queries_double(client): await client.queries.double_null() await client.queries.double_decimal_negative() await client.queries.double_decimal_positive() + @pytest.mark.asyncio async def test_queries_float_scientific(client): await client.queries.float_scientific_negative() await client.queries.float_scientific_positive() await client.queries.float_null() + @pytest.mark.asyncio async def test_queries_boolean(client): await client.queries.get_boolean_false() await client.queries.get_boolean_true() await client.queries.get_boolean_null() + @pytest.mark.asyncio async def test_queries_int(client): await client.queries.get_int_negative_one_million() await client.queries.get_int_one_million() await client.queries.get_int_null() + @pytest.mark.asyncio async def test_queries_long(client): await client.queries.get_negative_ten_billion() await client.queries.get_ten_billion() await client.queries.get_long_null() + @pytest.mark.asyncio async def test_queries_string(client): await client.queries.string_empty() await client.queries.string_null() await client.queries.string_url_encoded() + @pytest.mark.asyncio async def test_queries_enum(client): await client.queries.enum_valid(enum_query="green color") await client.queries.enum_null(enum_query=None) + @pytest.mark.asyncio async def test_queries_unicode(client): await client.queries.string_unicode() + @pytest.mark.asyncio async def test_array_string_csv(client, test_array_query): await client.queries.array_string_csv_empty(array_query=[]) await client.queries.array_string_csv_null(array_query=None) await client.queries.array_string_csv_valid(array_query=test_array_query) + @pytest.mark.asyncio async def test_array_string_miscellaneous(client, test_array_query): await client.queries.array_string_pipes_valid(array_query=test_array_query) await client.queries.array_string_ssv_valid(array_query=test_array_query) + @pytest.mark.asyncio @pytest.mark.skip(reason="https://github.com/aio-libs/aiohttp/issues/5904") async def test_array_string_tsv_valid(client, test_array_query): await client.queries.array_string_tsv_valid(test_array_query) + @pytest.mark.asyncio async def test_array_string_multi(multi_client, test_array_query): await multi_client.queries.array_string_multi_empty(array_query=[]) await multi_client.queries.array_string_multi_null() await multi_client.queries.array_string_multi_valid(array_query=test_array_query) + @pytest.mark.asyncio async def test_array_string_no_collection_format(client): - await client.queries.array_string_no_collection_format_empty(array_query=['hello', 'nihao', 'bonjour']) + await client.queries.array_string_no_collection_format_empty(array_query=["hello", "nihao", "bonjour"]) + @pytest.mark.asyncio async def test_get_all_with_values(client): @@ -242,6 +282,7 @@ async def test_get_all_with_values(client): local_string_query="localStringQuery", ) + @pytest.mark.asyncio async def test_get_global_and_local_query_null(client): client._config.global_string_path = "globalStringPath" @@ -252,6 +293,7 @@ async def test_get_global_and_local_query_null(client): local_string_query=None, ) + @pytest.mark.asyncio async def test_get_global_query_null(client): client._config.global_string_path = "globalStringPath" @@ -262,6 +304,7 @@ async def test_get_global_query_null(client): local_string_query="localStringQuery", ) + @pytest.mark.asyncio async def test_get_local_path_item_query_null(client): client._config.global_string_path = "globalStringPath" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_urlencoded.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_urlencoded.py index dc79f0d8cbc..259c404a9c4 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_urlencoded.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_urlencoded.py @@ -27,11 +27,13 @@ import pytest from bodyformurlencodeddataversiontolerant.aio import BodyFormsDataURLEncoded + @pytest.fixture async def client(): async with BodyFormsDataURLEncoded() as client: yield client + @pytest.mark.asyncio async def test_update_pet_with_form(client): await client.formdataurlencoded.update_pet_with_form( @@ -41,13 +43,12 @@ async def test_update_pet_with_form(client): "pet_food": "meat", "pet_age": 42, "name": "Fido", - } + }, ) + @pytest.mark.asyncio async def test_partial_constant_body(client): - await client.formdataurlencoded.partial_constant_body({ - "access_token": "foo", - "grant_type": "access_token", - "service": "bar" - }) + await client.formdataurlencoded.partial_constant_body( + {"access_token": "foo", "grant_type": "access_token", "service": "bar"} + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_validation.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_validation.py index a0c92faf2f4..6f101457e11 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_validation.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_validation.py @@ -30,15 +30,17 @@ import pytest + @pytest.fixture @async_generator async def client(): async with AutoRestValidationTest( - "abc123", - ) as client: + "abc123", + ) as client: client.api_version = "12-34-5678" await yield_(client) + @pytest.fixture def constant_body(): """This is NOT considering the constant body, this should work with @@ -46,16 +48,11 @@ def constant_body(): See https://github.com/Azure/autorest.modelerfour/issues/83 """ return { - 'child': { - 'constProperty': 'constant' - }, - 'constChild': { - 'constProperty': 'constant', - 'constProperty2': 'constant2' - }, - 'constInt': 0, - 'constString': 'constant', - 'constStringAsEnum': 'constant_string_as_enum' + "child": {"constProperty": "constant"}, + "constChild": {"constProperty": "constant", "constProperty2": "constant2"}, + "constInt": 0, + "constString": "constant", + "constStringAsEnum": "constant_string_as_enum", } @@ -63,35 +60,40 @@ def constant_body(): async def test_with_constant_in_path(client): await client.get_with_constant_in_path() + @pytest.mark.asyncio async def test_post_with_constant_in_body(client, constant_body): product = await client.post_with_constant_in_body(body=constant_body) assert product is not None -# Note: the client-side-validation is not supported for low-level client, + +# Note: the client-side-validation is not supported for low-level client, # so this request with faked path will be sent to testserver and get an ResourceNotFoundError @pytest.mark.asyncio async def test_fakedpath_validation(client): with pytest.raises(ResourceNotFoundError) as ex: await client.validation_of_method_parameters("1", 100) + @pytest.mark.skip(reason="Not generating models yet, can't validate") @pytest.mark.asyncio async def test_minimum_ex_validation(client, constant_body): with pytest.raises(ValueError) as ex: - constant_body['capacity'] = 0 + constant_body["capacity"] = 0 await client.validation_of_body("123", 150, constant_body) + @pytest.mark.skip(reason="Not generating models yet, can't validate") @pytest.mark.asyncio async def test_maximum_ex_validation(client, constant_body): with pytest.raises(ValueError) as ex: - constant_body['capacity'] = 100 + constant_body["capacity"] = 100 await client.validation_of_body("123", 150, constant_body) + @pytest.mark.skip(reason="Not generating models yet, can't validate") @pytest.mark.asyncio async def test_max_items_validation(client, constant_body): with pytest.raises(ValueError) as ex: - constant_body.display_names = ["item1","item2","item3","item4","item5","item6","item7"] + constant_body.display_names = ["item1", "item2", "item3", "item4", "item5", "item6", "item7"] await client.validation_of_body("123", 150, constant_body) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xml.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xml.py index f3441b0b45b..ae6a56d6b74 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xml.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xml.py @@ -44,6 +44,7 @@ async def client(): async def _assert_with_log(func, *args, **kwargs): def raise_for_status(response, deserialized, headers): response.http_response._internal_response.raise_for_status() + try: http_response = await func(*args, cls=raise_for_status, **kwargs) except Exception as err: @@ -80,7 +81,7 @@ async def test_simple(client): assert slide2.title == "Overview" assert len(slide2.items) == 3 assert slide2.items[0] == "Why WonderWidgets are great" - assert slide2.items[1] == '' + assert slide2.items[1] == "" assert slide2.items[2] == "Who buys WonderWidgets" await _assert_with_log(client.xml.put_simple, slideshow) @@ -90,7 +91,7 @@ async def test_simple(client): async def test_empty_child_element(client): banana = await client.xml.get_empty_child_element() # That's the point of this test, it was an empty node. - assert banana.flavor == '' + assert banana.flavor == "" await _assert_with_log(client.xml.put_empty_child_element, banana) @@ -133,8 +134,8 @@ async def test_get_empty(client): @pytest.mark.asyncio async def test_wrapped_lists(client): bananas = await client.xml.get_wrapped_lists() - assert bananas.good_apples == ['Fuji', 'Gala'] - assert bananas.bad_apples == ['Red Delicious'] + assert bananas.good_apples == ["Fuji", "Gala"] + assert bananas.bad_apples == ["Red Delicious"] await _assert_with_log(client.xml.put_wrapped_lists, bananas) @@ -168,9 +169,9 @@ async def test_list_blobs(client): assert blob.properties.content_length == 100 assert blob.properties.content_type == "text/html" # Check that an empty field in the XML is empty string - assert blob.properties.content_encoding == '' + assert blob.properties.content_encoding == "" assert blob.properties.content_language == "en-US" - assert blob.properties.content_md5 == '' + assert blob.properties.content_md5 == "" assert blob.properties.cache_control == "no-cache" assert blob.properties.blob_type == BlobType.block_blob # Check that a field NOT in the XML is None @@ -193,7 +194,7 @@ async def test_service_properties(client): async def test_acls(client): acls = await client.xml.get_acls() assert len(acls) == 1 - assert acls[0].id == 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' + assert acls[0].id == "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=" await _assert_with_log(client.xml.put_acls, acls) @@ -216,5 +217,5 @@ async def test_bytes(client): async def test_url(client): url_object = await client.xml.get_uri() assert isinstance(url_object, ModelWithUrlProperty) - assert url_object.url == 'https://myaccount.blob.core.windows.net/' + assert url_object.url == "https://myaccount.blob.core.windows.net/" await client.xml.put_uri(url_object) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xms_error.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xms_error.py index abe8d4f1d76..62c10733ea5 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xms_error.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/asynctests/test_xms_error.py @@ -31,19 +31,21 @@ from xmserrorresponseversiontolerant.aio import XMSErrorResponseExtensions + @pytest.fixture @async_generator async def client(): async with XMSErrorResponseExtensions(endpoint="http://localhost:3000") as client: await yield_(client) + @pytest.mark.asyncio async def test_get_by_pet_id_success(client): pet = await client.pet.get_pet_by_id("tommy") - assert pet['name'] == "Tommy Tomson" + assert pet["name"] == "Tommy Tomson" - await client.pet.get_pet_by_id('django') # no fail, 202 + await client.pet.get_pet_by_id("django") # no fail, 202 @pytest.mark.asyncio @@ -52,14 +54,15 @@ async def test_get_by_pet_id_discriminator(client): with pytest.raises(HttpResponseError) as excinfo: await client.pet.get_pet_by_id("coyoteUgly") - assert excinfo.value.response.json()['whatNotFound'] == 'AnimalNotFound' - assert excinfo.value.response.json()['reason'] == "the type of animal requested is not available" + assert excinfo.value.response.json()["whatNotFound"] == "AnimalNotFound" + assert excinfo.value.response.json()["reason"] == "the type of animal requested is not available" with pytest.raises(HttpResponseError) as excinfo: await client.pet.get_pet_by_id("weirdAlYankovic") - assert excinfo.value.response.json()['whatNotFound'] == 'InvalidResourceLink' - assert excinfo.value.response.json()['reason'] == "link to pet not found" + assert excinfo.value.response.json()["whatNotFound"] == "InvalidResourceLink" + assert excinfo.value.response.json()["reason"] == "link to pet not found" + @pytest.mark.asyncio async def test_get_by_pet_id_basic_types(client): @@ -74,26 +77,29 @@ async def test_get_by_pet_id_basic_types(client): assert excinfo.value.model is None # no model attached assert json.loads(excinfo.value.response.text()) == 123 + @pytest.mark.asyncio async def test_do_something_success(client): result = await client.pet.do_something("stay") with pytest.raises(KeyError): - result['actionResponse'] + result["actionResponse"] + @pytest.mark.asyncio async def test_do_something_error(client): with pytest.raises(HttpResponseError) as excinfo: await client.pet.do_something("jump") - assert excinfo.value.response.json()['errorType'] == 'PetSadError' - assert excinfo.value.response.json()['reason'] == "need more treats" + assert excinfo.value.response.json()["errorType"] == "PetSadError" + assert excinfo.value.response.json()["reason"] == "need more treats" with pytest.raises(ResourceNotFoundError) as excinfo: await client.pet.do_something("fetch") + @pytest.mark.asyncio async def test_error_deserialization_with_param_name_models(client): with pytest.raises(HttpResponseError) as excinfo: await client.pet.has_models_param() - assert excinfo.value.response.json()['errorType'] == 'PetSadError' + assert excinfo.value.response.json()["errorType"] == "PetSadError" assert excinfo.value.status_code == 500 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/conftest.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/conftest.py index fcdfaf056e6..64139e91e42 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/conftest.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/conftest.py @@ -39,21 +39,26 @@ cwd = dirname(realpath(__file__)) -#Ideally this would be in a common helper library shared between the tests + +# Ideally this would be in a common helper library shared between the tests def start_server_process(): - cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format(cwd) - if os.name == 'nt': #On windows, subprocess creation works without being in the shell + cmd = "node {}/../../../../node_modules/@microsoft.azure/autorest.testserver/dist/cli/cli.js run --appendCoverage".format( + cwd + ) + if os.name == "nt": # On windows, subprocess creation works without being in the shell return subprocess.Popen(cmd) - return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) #On linux, have to set shell=True + return subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # On linux, have to set shell=True + -#Ideally this would be in a common helper library shared between the tests +# Ideally this would be in a common helper library shared between the tests def terminate_server_process(process): - if os.name == 'nt': + if os.name == "nt": process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) # Send the signal to all the process groups + @pytest.fixture(scope="session") def testserver(): """Start the Autorest testserver.""" @@ -78,13 +83,16 @@ def on_response(self, request, response, **kwargs): if "Set-Cookie" in http_response.headers: self._current_cookie = http_response.headers["Set-Cookie"] + @pytest.fixture() def cookie_policy(): return CookiePolicy() + # the token value shall keep same with https://github.com/Azure/autorest.testserver/tree/main/src/test-routes/security.ts def generate_token(*scopes) -> AccessToken: - return AccessToken(token=''.join(scopes), expires_on=1800) + return AccessToken(token="".join(scopes), expires_on=1800) + @pytest.fixture() def credential(): @@ -92,12 +100,15 @@ class FakeCredential: @staticmethod def get_token(*scopes) -> AccessToken: return generate_token(*scopes) + return FakeCredential() + @pytest.fixture() def credential_async(): class FakeCredentialAsync: @staticmethod async def get_token(*scopes) -> AccessToken: return generate_token(*scopes) + return FakeCredentialAsync() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/serializer.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/serializer.py index d96a0bb9dec..d3b815d5e4b 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/serializer.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/serializer.py @@ -34,6 +34,7 @@ try: from datetime import timezone as _FixedOffset except ImportError: # Python 2.7 + class _FixedOffset(datetime.tzinfo): # type: ignore """Fixed offset in minutes east from UTC. Copy/pasted from Python doc @@ -47,7 +48,7 @@ def utcoffset(self, dt): return self.__offset def tzname(self, dt): - return str(self.__offset.total_seconds()/3600) + return str(self.__offset.total_seconds() / 3600) def __repr__(self): return "".format(self.tzname(None)) @@ -58,6 +59,7 @@ def dst(self, dt): def __getinitargs__(self): return (self.__offset,) + class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" @@ -73,37 +75,53 @@ def dst(self, dt): """No daylight saving for UTC.""" return datetime.timedelta(hours=1) + try: from datetime import timezone + TZ_UTC = timezone.utc # type: ignore except ImportError: TZ_UTC = UTC() # type: ignore -DAYS = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", - 4: "Fri", 5: "Sat", 6: "Sun"} -MONTHS = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", - 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} +DAYS = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} +MONTHS = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", +} + +VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") -VALID_DATE = re.compile( - r'\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}' - r'\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?') def serialize_base64(attr): - encoded = b64encode(attr).decode('ascii') - return encoded.strip('=').replace('+', '-').replace('/', '_') + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + def deserialize_base64(attr): - padding = '=' * (3 - (len(attr) + 3) % 4) + padding = "=" * (3 - (len(attr) + 3) % 4) attr = attr + padding - encoded = attr.replace('-', '+').replace('_', '/') + encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) + def deserialize_date(attr): return isodate.parse_date(attr) + def deserialize_datetime(attr): return isodate.parse_datetime(attr) + def serialize_rfc(attr): try: utc = attr.utctimetuple() @@ -111,11 +129,10 @@ def serialize_rfc(attr): raise TypeError("RFC1123 object must be valid Datetime object.") return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - DAYS[utc.tm_wday], utc.tm_mday, - MONTHS[utc.tm_mon], utc.tm_year, - utc.tm_hour, utc.tm_min, utc.tm_sec + DAYS[utc.tm_wday], utc.tm_mday, MONTHS[utc.tm_mon], utc.tm_year, utc.tm_hour, utc.tm_min, utc.tm_sec ) + def serialize_iso(attr): if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -123,13 +140,14 @@ def serialize_iso(attr): if utc.tm_year > 9999 or utc.tm_year < 1: raise OverflowError("Hit max or min date") - microseconds = str(attr.microsecond).rjust(6,'0').rstrip('0').ljust(3, '0') + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") if microseconds: - microseconds = '.'+microseconds + microseconds = "." + microseconds date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, - utc.tm_hour, utc.tm_min, utc.tm_sec) - return date + microseconds + 'Z' + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + def deserialize_iso(attr): if isinstance(attr, ET.Element): @@ -139,7 +157,7 @@ def deserialize_iso(attr): if not match: raise ValueError("Invalid datetime string: " + attr) - check_decimal = attr.split('.') + check_decimal = attr.split(".") if len(check_decimal) > 1: decimal_str = "" for digit in check_decimal[1]: @@ -156,61 +174,70 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") return date_obj + def deserialize_bytearray(attr): if isinstance(attr, ET.Element): attr = attr.text return bytearray(b64decode(attr)) + def serialize_bytearray(attr): return b64encode(attr).decode() + def serialize_date(attr): if isinstance(attr, str): attr = isodate.parse_date(attr) t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) return t + def deserialize_duration(attr): if isinstance(attr, ET.Element): attr = attr.text return isodate.parse_duration(attr) + def serialize_duration(attr): if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + def deserialize_rfc(attr): if isinstance(attr, ET.Element): attr = attr.text parsed_date = email.utils.parsedate_tz(attr) date_obj = datetime.datetime( - *parsed_date[:6], - tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0)/60)) + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) return date_obj + def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) return datetime.datetime.fromtimestamp(attr, TZ_UTC) + def serialize_unix(attr): if isinstance(attr, int): return attr return int(calendar.timegm(attr.utctimetuple())) + def deserialize_time(attr): if isinstance(attr, ET.Element): attr = attr.text return isodate.parse_time(attr) + def serialize_time(attr): if isinstance(attr, str): attr = isodate.parse_time(attr) t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) if attr.microsecond: t += ".{:02}".format(attr.microsecond) - return t \ No newline at end of file + return t diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_additional_properties.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_additional_properties.py index 5b3d59113cb..2d5c8db9434 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_additional_properties.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_additional_properties.py @@ -28,89 +28,71 @@ from additionalpropertiesversiontolerant import AdditionalPropertiesClient + @pytest.fixture def client(): with AdditionalPropertiesClient() as client: yield client + def test_create_ap_true(client): input_ap_true = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - }, + "birthdate": "2017-12-13T02:29:51Z", + "complexProperty": {"color": "Red"}, "id": 1, "name": "Puppy", } output_ap_true = client.pets.create_ap_true(input_ap_true) - assert output_ap_true['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true["birthdate"] == "2017-12-13T02:29:51Z" + def test_create_cat_ap_true(client): input_ap_true = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': {'color': 'Red'}, - 'id': 1, - 'name': 'Lisa', - 'friendly': True + "birthdate": "2017-12-13T02:29:51Z", + "complexProperty": {"color": "Red"}, + "id": 1, + "name": "Lisa", + "friendly": True, } output_ap_true = client.pets.create_cat_ap_true(input_ap_true) - assert output_ap_true['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_true["birthdate"] == "2017-12-13T02:29:51Z" + def test_create_ap_object(client): input_ap_obj = { "id": 2, "name": "Hira", - 'siblings': [{ - 'id': 1, - 'name': 'Puppy', - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - }], - 'picture': '//////4=' + "siblings": [ + {"id": 1, "name": "Puppy", "birthdate": "2017-12-13T02:29:51Z", "complexProperty": {"color": "Red"}} + ], + "picture": "//////4=", } output_ap_obj = client.pets.create_ap_object(input_ap_obj) - assert output_ap_obj['siblings'][0]['birthdate'] == '2017-12-13T02:29:51Z' + assert output_ap_obj["siblings"][0]["birthdate"] == "2017-12-13T02:29:51Z" + def test_create_ap_string(client): - input_ap_str = { - "id": 3, - "name": 'Tommy', - 'color': 'red', - 'weight': '10 kg', - 'city': 'Bombay' - } + input_ap_str = {"id": 3, "name": "Tommy", "color": "red", "weight": "10 kg", "city": "Bombay"} output_ap_str = client.pets.create_ap_string(input_ap_str) - assert output_ap_str['color'] == 'red' + assert output_ap_str["color"] == "red" + def test_create_ap_in_properties(client): - input_ap_int = { - "id": 4, - "name": 'Bunny', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } - } + input_ap_int = {"id": 4, "name": "Bunny", "additionalProperties": {"height": 5.61, "weight": 599, "footsize": 11.5}} output_ap_int = client.pets.create_ap_in_properties(input_ap_int) - assert output_ap_int['additionalProperties']['weight'] == 599 + assert output_ap_int["additionalProperties"]["weight"] == 599 + def test_create_ap_in_properties_with_ap_string(client): input_ap_str_add = { "id": 5, - "name": 'Funny', - "@odata.location":'westus', - 'color': 'red', - 'city': 'Seattle', - 'food': 'tikka masala', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } + "name": "Funny", + "@odata.location": "westus", + "color": "red", + "city": "Seattle", + "food": "tikka masala", + "additionalProperties": {"height": 5.61, "weight": 599, "footsize": 11.5}, } output_ap_str_add = client.pets.create_ap_in_properties_with_ap_string(input_ap_str_add) - assert output_ap_str_add['color'] == 'red' - assert output_ap_str_add['additionalProperties']['weight'] == 599 + assert output_ap_str_add["color"] == "red" + assert output_ap_str_add["additionalProperties"]["weight"] == 599 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_anything.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_anything.py index 7f087e8cd51..770348b7263 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_anything.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_anything.py @@ -26,25 +26,32 @@ import pytest from anythingversiontolerant import AnythingClient + @pytest.fixture def client(): with AnythingClient() as client: yield client + def test_get_string(client): - assert client.get_string() == 'anything' + assert client.get_string() == "anything" + def test_put_string(client): client.put_string(input="anything") + def test_get_object(client): assert client.get_object() == {"message": "An object was successfully returned"} + def test_put_object(client): - client.put_object({'foo': 'bar'}) + client.put_object({"foo": "bar"}) + def test_get_array(client): - assert client.get_array() == ['foo', 'bar'] + assert client.get_array() == ["foo", "bar"] + def test_put_array(client): - client.put_array(['foo', 'bar']) + client.put_array(["foo", "bar"]) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_array.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_array.py index 75d9d6c4efa..a5ec189f60b 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_array.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_array.py @@ -35,11 +35,13 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATArrayService() as client: yield client + @pytest.fixture def datetimes(): datetime1 = isodate.parse_datetime("2000-12-01T00:00:01Z") @@ -47,63 +49,87 @@ def datetimes(): datetime3 = isodate.parse_datetime("1492-10-12T10:15:01Z") return [datetime1, datetime2, datetime3] + @pytest.fixture def products(): prod1 = {"integer": 1, "string": "2"} prod2 = {"integer": 3, "string": "4"} prod3 = {"integer": 5, "string": "6"} return [prod1, prod2, prod3] + + @pytest.fixture def listdict(): - return [{"1": "one", "2": "two", "3": "three"}, - {"4": "four", "5": "five", "6": "six"}, - {"7": "seven", "8": "eight", "9": "nine"}] + return [ + {"1": "one", "2": "two", "3": "three"}, + {"4": "four", "5": "five", "6": "six"}, + {"7": "seven", "8": "eight", "9": "nine"}, + ] def test_empty(client): - assert [] == client.array.get_empty() + assert [] == client.array.get_empty() assert client.array.get_null() is None client.array.put_empty([]) + def test_boolean_tfft(client): - assert [True, False, False, True] == client.array.get_boolean_tfft() + assert [True, False, False, True] == client.array.get_boolean_tfft() client.array.put_boolean_tfft([True, False, False, True]) + def test_integer_valid(client): - assert [1, -1, 3, 300] == client.array.get_integer_valid() + assert [1, -1, 3, 300] == client.array.get_integer_valid() client.array.put_integer_valid([1, -1, 3, 300]) + def test_long_valid(client): - assert [1, -1, 3, 300] == client.array.get_long_valid() + assert [1, -1, 3, 300] == client.array.get_long_valid() client.array.put_long_valid([1, -1, 3, 300]) + def test_float_valid(client): - assert [0, -0.01, -1.2e20] == client.array.get_float_valid() + assert [0, -0.01, -1.2e20] == client.array.get_float_valid() client.array.put_float_valid([0, -0.01, -1.2e20]) + def test_double_valid(client): - assert [0, -0.01, -1.2e20] == client.array.get_double_valid() + assert [0, -0.01, -1.2e20] == client.array.get_double_valid() client.array.put_double_valid([0, -0.01, -1.2e20]) + def test_string_valid(client): - assert ["foo1", "foo2", "foo3"] == client.array.get_string_valid() + assert ["foo1", "foo2", "foo3"] == client.array.get_string_valid() client.array.put_string_valid(["foo1", "foo2", "foo3"]) + def test_get_string_with_null(client): - assert ["foo", None, "foo2"] == client.array.get_string_with_null() + assert ["foo", None, "foo2"] == client.array.get_string_with_null() + def test_get_string_with_invalid(client): - assert ["foo", 123, "foo2"] == client.array.get_string_with_invalid() + assert ["foo", 123, "foo2"] == client.array.get_string_with_invalid() + def test_uuid_valid(client): - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"] == client.array.get_uuid_valid() - client.array.put_uuid_valid(["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"]) + assert [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] == client.array.get_uuid_valid() + client.array.put_uuid_valid( + [ + "6dcc7237-45fe-45c4-8a6b-3a8a3f625652", + "d1399005-30f7-40d6-8da6-dd7c89ad34db", + "f42f6aa1-a5bc-4ddf-907e-5f915de43205", + ] + ) + def test_get_uuid_invalid_chars(client): - #Handles invalid characters without error because of no guid class - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == client.array.get_uuid_invalid_chars() + # Handles invalid characters without error because of no guid class + assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == client.array.get_uuid_invalid_chars() + def test_date_valid(client): date1 = isodate.parse_date("2000-12-01") @@ -111,27 +137,31 @@ def test_date_valid(client): date3 = isodate.parse_date("1492-10-12") date_array = client.array.get_date_valid() - assert date_array, [date1, date2 == date3] + assert date_array, [date1, date2 == date3] client.array.put_date_valid([str(date1), str(date2), str(date3)]) + def test_date_time_valid(client, datetimes): dt_array = client.array.get_date_time_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] client.array.put_date_time_valid([Serializer.serialize_iso(datetime) for datetime in datetimes]) + def test_date_time_rfc1123_valid(client, datetimes): dt_array = client.array.get_date_time_rfc1123_valid() - assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] + assert dt_array, [datetimes[0], datetimes[1] == datetimes[2]] client.array.put_date_time_rfc1123_valid([Serializer.serialize_rfc(datetime) for datetime in datetimes]) + def test_duration_valid(client): duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration2 = timedelta(days=5, hours=1) dur_array = client.array.get_duration_valid() - assert dur_array, [duration1 == duration2] + assert dur_array, [duration1 == duration2] client.array.put_duration_valid([isodate.duration_isoformat(duration1), isodate.duration_isoformat(duration2)]) + def test_byte_valid(client): bytes1 = bytearray([0x0FF, 0x0FF, 0x0FF, 0x0FA]) bytes2 = bytearray([0x01, 0x02, 0x03]) @@ -140,134 +170,165 @@ def test_byte_valid(client): client.array.put_byte_valid([b64encode(b).decode() for b in [bytes1, bytes2, bytes3]]) bytes_array = client.array.get_byte_valid() - assert bytes_array, [bytes1, bytes2 == bytes3] + assert bytes_array, [bytes1, bytes2 == bytes3] + def test_get_byte_invalid_null(client): bytes_array = client.array.get_byte_invalid_null() - assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] + assert bytes_array, [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] + def test_get_complex_null(client): assert client.array.get_complex_null() is None + def test_get_complex_empty(client): - assert [] == client.array.get_complex_empty() + assert [] == client.array.get_complex_empty() + def test_complex_valid(client, products): client.array.put_complex_valid(products) - assert products == client.array.get_complex_valid() + assert products == client.array.get_complex_valid() + def test_get_array_valid(client): listlist = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] client.array.put_array_valid(listlist) - assert listlist == client.array.get_array_valid() + assert listlist == client.array.get_array_valid() + def test_dictionary_valid(client, listdict): client.array.put_dictionary_valid(listdict) - assert listdict == client.array.get_dictionary_valid() + assert listdict == client.array.get_dictionary_valid() + def test_get_complex_item_null(client, products): products_null = [products[0], None, products[2]] - assert products_null == client.array.get_complex_item_null() + assert products_null == client.array.get_complex_item_null() + def test_get_complex_item_empty(client, products): products_empty = [products[0], {}, products[2]] - assert products_empty == client.array.get_complex_item_empty() + assert products_empty == client.array.get_complex_item_empty() + def test_get_array_null(client): assert client.array.get_array_null() is None + def test_get_array_empty(client): - assert [] == client.array.get_array_empty() + assert [] == client.array.get_array_empty() + def test_get_array_item_null(client): listlist2 = [["1", "2", "3"], None, ["7", "8", "9"]] - assert listlist2 == client.array.get_array_item_null() + assert listlist2 == client.array.get_array_item_null() + def test_get_array_item_empty(client): listlist3 = [["1", "2", "3"], [], ["7", "8", "9"]] - assert listlist3 == client.array.get_array_item_empty() + assert listlist3 == client.array.get_array_item_empty() + def test_get_dictionary_and_dictionary_item_null(client, listdict): assert client.array.get_dictionary_null() is None listdict[1] = None - assert listdict == client.array.get_dictionary_item_null() + assert listdict == client.array.get_dictionary_item_null() + def test_get_dictionary_and_dictionary_item_empty(client, listdict): - assert [] == client.array.get_dictionary_empty() + assert [] == client.array.get_dictionary_empty() listdict[1] = {} - assert listdict == client.array.get_dictionary_item_empty() + assert listdict == client.array.get_dictionary_item_empty() + def test_array_get_invalid(client): with pytest.raises(DecodeError): client.array.get_invalid() + def test_array_get_boolean_invalid_null(client): - assert client.array.get_boolean_invalid_null(), [True, None == False] + assert client.array.get_boolean_invalid_null(), [True, None == False] + def test_array_get_boolean_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert client.array.get_boolean_invalid_string() == [True, "boolean", False] + def test_array_get_int_invalid_null(client): - assert client.array.get_int_invalid_null(), [1, None == 0] + assert client.array.get_int_invalid_null(), [1, None == 0] + def test_array_get_int_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert client.array.get_int_invalid_string() == [1, "integer", 0] + def test_array_get_long_invalid_null(client): - assert client.array.get_long_invalid_null(), [1, None == 0] + assert client.array.get_long_invalid_null(), [1, None == 0] + def test_array_get_long_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert client.array.get_long_invalid_string() == [1, "integer", 0] + def test_array_get_float_invalid_null(client): - assert client.array.get_float_invalid_null(), [0.0, None == -1.2e20] + assert client.array.get_float_invalid_null(), [0.0, None == -1.2e20] + def test_array_get_float_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert client.array.get_float_invalid_string() == [1, "number", 0] + def test_array_get_double_invalid_null(client): - assert client.array.get_double_invalid_null(), [0.0, None == -1.2e20] + assert client.array.get_double_invalid_null(), [0.0, None == -1.2e20] + def test_array_get_double_invalid_string(client): # don't raise deserialization error bc we're not msrest deserializing assert client.array.get_double_invalid_string() == [1, "number", 0] + def test_array_get_string_with_invalid(client): - assert client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] + assert client.array.get_string_with_invalid(), ["foo", "123" == "foo2"] + def test_array_get_date_invalid_null(client): d_array = client.array.get_date_invalid_null() - assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] + assert d_array, [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] + def test_array_get_date_invalid_chars(client): # don't raise deserialization error bc we're not msrest deserializing assert client.array.get_date_invalid_chars() == ["2011-03-22", "date"] + def test_array_get_date_time_invalid_null(client): dt_array = client.array.get_date_time_invalid_null() - assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] + assert dt_array, [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] + def test_array_get_date_time_invalid_chars(client): # don't raise deserialization error bc we're not msrest deserializing - assert client.array.get_date_time_invalid_chars() == ['2000-12-01t00:00:01z', 'date-time'] + assert client.array.get_date_time_invalid_chars() == ["2000-12-01t00:00:01z", "date-time"] + def test_array_get_base64_url(client): - test_array = ['a string that gets encoded with base64url'.encode(), - 'test string'.encode(), - 'Lorem ipsum'.encode()] - assert [deserialize_base64(entry) for entry in client.array.get_base64_url()] == test_array + test_array = ["a string that gets encoded with base64url".encode(), "test string".encode(), "Lorem ipsum".encode()] + assert [deserialize_base64(entry) for entry in client.array.get_base64_url()] == test_array + def test_array_enum_valid(client): array = client.array.get_enum_valid() client.array.put_enum_valid(array) + def test_array_string_enum_valid(client): array = client.array.get_string_enum_valid() client.array.put_string_enum_valid(array) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_binary.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_binary.py index 85da29ddeaa..886baa7df3f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_binary.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_binary.py @@ -28,6 +28,7 @@ from bodybinaryversiontolerant import BinaryWithContentTypeApplicationJson from azure.core.exceptions import HttpResponseError + @pytest.fixture def client(): with BinaryWithContentTypeApplicationJson() as client: @@ -37,9 +38,11 @@ def client(): def test_upload_file(client): client.upload.file(b'{"more": "cowbell"}') + def test_upload_binary(client): client.upload.binary(b"Hello, world!") + def test_error(client: BinaryWithContentTypeApplicationJson): with pytest.raises(HttpResponseError): client.download.error_stream() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_bool.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_bool.py index 2427944b9ab..256cd816726 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_bool.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_bool.py @@ -29,26 +29,33 @@ import pytest + @pytest.fixture def client(): with AutoRestBoolTestService() as client: yield client + def test_model_get_true(client): assert client.bool.get_true() + def test_model_get_false(client): assert not client.bool.get_false() + def test_model_get_null(client): client.bool.get_null() + def test_model_put_false(client): client.bool.put_false() + def test_model_put_true(client): client.bool.put_true() + def test_model_get_invalid(client): with pytest.raises(DecodeError): client.bool.get_invalid() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_byte.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_byte.py index f9c76b298eb..154174b3802 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_byte.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_byte.py @@ -31,6 +31,7 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATByteService() as client: @@ -42,11 +43,14 @@ def test_non_ascii(client): client.byte.put_non_ascii(serialize_bytearray(tests)) assert tests == deserialize_bytearray(client.byte.get_non_ascii()) + def test_get_null(client): assert client.byte.get_null() is None + def test_get_empty(client): assert bytearray() == deserialize_base64(client.byte.get_empty()) + def test_get_invalid(client): assert client.byte.get_invalid() == "::::SWAGGER::::" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_client_enum.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_client_enum.py index 44cded4e9b1..fa999c57af5 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_client_enum.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_client_enum.py @@ -26,10 +26,12 @@ import pytest from clientenumversiontolerant import ClientWithEnum, models + @pytest.fixture def client(): with ClientWithEnum(x_ms_enum=models.Enum0.SINGLE) as client: yield client + def test_head(client): client.head() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_complex.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_complex.py index d2fcba2c386..dbcb64ac707 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_complex.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_complex.py @@ -35,34 +35,39 @@ from bodycomplexversiontolerant import AutoRestComplexTestService from azure.core.pipeline.policies import CustomHookPolicy + class UTC(tzinfo): - def utcoffset(self,dt): - return timedelta(hours=0,minutes=0) + def utcoffset(self, dt): + return timedelta(hours=0, minutes=0) - def tzname(self,dt): + def tzname(self, dt): return "Z" - def dst(self,dt): + def dst(self, dt): return timedelta(0) + import pytest + @pytest.fixture def client(): with AutoRestComplexTestService() as client: yield client + @pytest.fixture def min_date(): min_date = datetime.min return min_date.replace(tzinfo=UTC()) + def test_basic_get_and_put_valid(client: AutoRestComplexTestService): # GET basic/valid basic_result = client.basic.get_valid() - assert 2 == basic_result['id'] - assert "abc" == basic_result['name'] - assert "YELLOW" == basic_result['color'] + assert 2 == basic_result["id"] + assert "abc" == basic_result["name"] + assert "YELLOW" == basic_result["color"] # PUT basic/valid basic_result = { @@ -72,129 +77,131 @@ def test_basic_get_and_put_valid(client: AutoRestComplexTestService): } client.basic.put_valid(basic_result) + def test_basic_get_empty(client): # GET basic/empty basic_result = client.basic.get_empty() assert basic_result == {} + def test_basic_get_null(client): # GET basic/null basic_result = client.basic.get_null() - assert basic_result['id'] is None - assert basic_result['name'] is None + assert basic_result["id"] is None + assert basic_result["name"] is None + def test_basic_get_not_provided(client): # GET basic/notprovided basic_result = client.basic.get_not_provided() assert basic_result is None + def test_basic_get_invalid(client): # GET basic/invalid basic_result = client.basic.get_invalid() # it's deserialized as invalid bc the id is not a number # with legacy, we don't care though - assert basic_result['id'] == 'a' - assert basic_result['name'] == 'abc' + assert basic_result["id"] == "a" + assert basic_result["name"] == "abc" + # COMPLEX TYPE WITH PRIMITIVE PROPERTIES def test_primitive_get_and_put_int(client): # GET primitive/integer int_result = client.primitive.get_int() - assert -1 == int_result['field1'] - assert 2 == int_result['field2'] + assert -1 == int_result["field1"] + assert 2 == int_result["field2"] # PUT primitive/integer - int_request = {'field1':-1, 'field2':2} + int_request = {"field1": -1, "field2": 2} client.primitive.put_int(int_request) + def test_primitive_get_and_put_long(client): # GET primitive/long long_result = client.primitive.get_long() - assert 1099511627775 == long_result['field1'] - assert -999511627788 == long_result['field2'] + assert 1099511627775 == long_result["field1"] + assert -999511627788 == long_result["field2"] # PUT primitive/long - long_request = {'field1':1099511627775, 'field2':-999511627788} + long_request = {"field1": 1099511627775, "field2": -999511627788} client.primitive.put_long(long_request) + def test_primitive_get_and_put_float(client): # GET primitive/float float_result = client.primitive.get_float() - assert 1.05 == float_result['field1'] - assert -0.003 == float_result['field2'] + assert 1.05 == float_result["field1"] + assert -0.003 == float_result["field2"] # PUT primitive/float - float_request = { - "field1": 1.05, - "field2": -0.003 - } + float_request = {"field1": 1.05, "field2": -0.003} client.primitive.put_float(float_request) + def test_primitive_get_and_put_double(client): # GET primitive/double double_result = client.primitive.get_double() - assert 3e-100 == double_result['field1'] - assert -5e-57 == double_result['field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose'] + assert 3e-100 == double_result["field1"] + assert ( + -5e-57 + == double_result[ + "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose" + ] + ) # PUT primitive/double double_request = { "field1": 3e-100, - "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose": -5e-57 + "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose": -5e-57, } client.primitive.put_double(double_request) + def test_primitive_get_and_put_bool(client): # GET primitive/bool bool_result = client.primitive.get_bool() - assert bool_result['field_true'] - assert not bool_result['field_false'] + assert bool_result["field_true"] + assert not bool_result["field_false"] # PUT primitive/bool - bool_request = { - "field_true": True, - "field_false": False - } + bool_request = {"field_true": True, "field_false": False} client.primitive.put_bool(bool_request) + def test_primitive_get_and_put_string(client): # GET primitive/string string_result = client.primitive.get_string() - assert "goodrequest" == string_result['field'] - assert "" == string_result['empty'] - assert string_result['null'] is None + assert "goodrequest" == string_result["field"] + assert "" == string_result["empty"] + assert string_result["null"] is None # PUT primitive/string - string_request = { - "null": None, - "empty": "", - "field": "goodrequest" - } + string_request = {"null": None, "empty": "", "field": "goodrequest"} client.primitive.put_string(string_request) + def test_primitive_get_and_put_date(client): # GET primitive/date date_result = client.primitive.get_date() - assert isodate.parse_date("0001-01-01") == isodate.parse_date(date_result['field']) - assert isodate.parse_date("2016-02-29") == isodate.parse_date(date_result['leap']) + assert isodate.parse_date("0001-01-01") == isodate.parse_date(date_result["field"]) + assert isodate.parse_date("2016-02-29") == isodate.parse_date(date_result["leap"]) - date_request = { - "field": '0001-01-01', - "leap": '2016-02-29' - } + date_request = {"field": "0001-01-01", "leap": "2016-02-29"} client.primitive.put_date(date_request) + def test_primitive_get_and_put_date_time(client, min_date): # GET primitive/datetime datetime_result = client.primitive.get_date_time() - assert min_date == Deserializer.deserialize_iso(datetime_result['field']) + assert min_date == Deserializer.deserialize_iso(datetime_result["field"]) - datetime_request = { - "field": "0001-01-01T00:00:00Z", - "now": "2015-05-18T18:38:00Z" - } + datetime_request = {"field": "0001-01-01T00:00:00Z", "now": "2015-05-18T18:38:00Z"} client.primitive.put_date_time(datetime_request) + def test_primitive_get_and_put_date_time_rfc1123(client): # GET primitive/datetimerfc1123 datetimerfc1123_result = client.primitive.get_date_time_rfc1123() @@ -202,145 +209,161 @@ def test_primitive_get_and_put_date_time_rfc1123(client): # we are not using the min date of year 1 because of the latest msrest update # with msrest update, minimal year we can parse is 100, instead of 1 min_date = datetime(2001, 1, 1) - assert min_date.replace(tzinfo=UTC()) == Deserializer.deserialize_rfc(datetimerfc1123_result['field']) + assert min_date.replace(tzinfo=UTC()) == Deserializer.deserialize_rfc(datetimerfc1123_result["field"]) # we can still model year 1 though with the latest msrest update datetime_request = { "field": Serializer.serialize_rfc(isodate.parse_datetime("0001-01-01T00:00:00Z")), - "now": Serializer.serialize_rfc(isodate.parse_datetime("2015-05-18T11:38:00Z")) + "now": Serializer.serialize_rfc(isodate.parse_datetime("2015-05-18T11:38:00Z")), } client.primitive.put_date_time_rfc1123(datetime_request) + def test_primitive_get_and_put_duration(client): # GET primitive/duration expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration_result = client.primitive.get_duration() - assert expected == Deserializer.deserialize_duration(duration_result['field']) + assert expected == Deserializer.deserialize_duration(duration_result["field"]) client.primitive.put_duration({"field": Serializer.serialize_duration(expected)}) + def test_primitive_get_and_put_byte(client): # GET primitive/byte byte_result = client.primitive.get_byte() valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - assert valid_bytes == bytearray(b64decode(byte_result['field'])) + assert valid_bytes == bytearray(b64decode(byte_result["field"])) # PUT primitive/byte client.primitive.put_byte({"field": b64encode(valid_bytes).decode()}) + # COMPLEX TYPE WITH READ ONLY PROPERTIES + def test_readonlyproperty_get_and_put_valid(client): # GET readonly/valid - valid_obj = {"size": 2, 'id': '1234'} + valid_obj = {"size": 2, "id": "1234"} readonly_result = client.readonlyproperty.get_valid() - assert readonly_result == valid_obj + assert readonly_result == valid_obj # PUT readonly/valid readonly_result = client.readonlyproperty.put_valid(2) assert readonly_result is None + # COMPLEX TYPE WITH ARRAY PROPERTIES + def test_array_get_and_put_valid(client): # GET array/valid array_result = client.array.get_valid() - assert 5 == len(array_result['array']) + assert 5 == len(array_result["array"]) - array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", - "The quick brown fox jumps over the lazy dog"] - assert array_result['array'] == array_value + array_value = ["1, 2, 3, 4", "", None, "&S#$(*Y", "The quick brown fox jumps over the lazy dog"] + assert array_result["array"] == array_value # PUT array/valid client.array.put_valid({"array": array_value}) + def test_array_get_and_put_empty(client): # GET array/empty array_result = client.array.get_empty() - assert 0 == len(array_result['array']) + assert 0 == len(array_result["array"]) # PUT array/empty client.array.put_empty({"array": []}) + def test_array_get_not_provided(client): # Get array/notprovided assert client.array.get_not_provided() == {} + # COMPLEX TYPE WITH DICTIONARY PROPERTIES + def test_dictionary_get_and_put_valid(client): # GET dictionary/valid dict_result = client.dictionary.get_valid() - assert 5 == len(dict_result['defaultProgram']) + assert 5 == len(dict_result["defaultProgram"]) - dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} - assert dict_val == dict_result['defaultProgram'] + dict_val = {"txt": "notepad", "bmp": "mspaint", "xls": "excel", "exe": "", "": None} + assert dict_val == dict_result["defaultProgram"] # PUT dictionary/valid client.dictionary.put_valid({"defaultProgram": dict_val}) + def test_dictionary_get_and_put_empty(client): # GET dictionary/empty dict_result = client.dictionary.get_empty() - assert 0 == len(dict_result['defaultProgram']) + assert 0 == len(dict_result["defaultProgram"]) # PUT dictionary/empty client.dictionary.put_empty({"defaultProgram": {}}) + def test_dictionary_get_and_null(client): # GET dictionary/null - assert client.dictionary.get_null()['defaultProgram'] is None + assert client.dictionary.get_null()["defaultProgram"] is None + def test_dictionary_get_not_provided(client): # GET dictionary/notprovided assert client.dictionary.get_not_provided() == {} + # COMPLEX TYPES THAT INVOLVE INHERITANCE + def test_inheritance_get_and_put_valid(client): # GET inheritance/valid inheritance_result = client.inheritance.get_valid() - assert 2 == inheritance_result['id'] - assert "Siameeee" == inheritance_result['name'] - assert -1 == inheritance_result['hates'][1]['id'] - assert "Tomato" == inheritance_result['hates'][1]['name'] + assert 2 == inheritance_result["id"] + assert "Siameeee" == inheritance_result["name"] + assert -1 == inheritance_result["hates"][1]["id"] + assert "Tomato" == inheritance_result["hates"][1]["name"] # PUT inheritance/valid request = { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [{"id": 1, "name": "Potato", "food": "tomato"}, - {"id": -1, "name": "Tomato", "food": "french fries"}] - } + "id": 2, + "name": "Siameeee", + "color": "green", + "breed": "persian", + "hates": [{"id": 1, "name": "Potato", "food": "tomato"}, {"id": -1, "name": "Tomato", "food": "french fries"}], + } client.inheritance.put_valid(request) + # COMPLEX TYPES THAT INVOLVE POLYMORPHISM + def test_get_composed_with_discriminator(client): result = client.polymorphism.get_composed_with_discriminator() - assert result['sampleSalmon']['fish.type'] == "DotSalmon" + assert result["sampleSalmon"]["fish.type"] == "DotSalmon" + def test_get_composed_without_discriminator(client): result = client.polymorphism.get_composed_without_discriminator() with pytest.raises(KeyError): - result['sampleSalmon']['fish.type'] # shouldn't have a discriminator + result["sampleSalmon"]["fish.type"] # shouldn't have a discriminator + def test_polymorphism_get_and_put_valid(client): # GET polymorphism/valid result = client.polymorphism.get_valid() assert result is not None - assert result['location'] == "alaska" - assert len(result['siblings']) == 3 - assert result['siblings'][0]['fishtype'] == 'shark' - assert result['siblings'][1]['fishtype'] == 'sawshark' - assert result['siblings'][2]['fishtype'] == 'goblin' - assert result['siblings'][0]['age'] == 6 - assert result['siblings'][1]['age'] == 105 - assert result['siblings'][2]['age'] == 1 - + assert result["location"] == "alaska" + assert len(result["siblings"]) == 3 + assert result["siblings"][0]["fishtype"] == "shark" + assert result["siblings"][1]["fishtype"] == "sawshark" + assert result["siblings"][2]["fishtype"] == "goblin" + assert result["siblings"][0]["age"] == 6 + assert result["siblings"][1]["age"] == 105 + assert result["siblings"][2]["age"] == 1 # PUT polymorphism/valid request = { @@ -353,7 +376,7 @@ def test_polymorphism_get_and_put_valid(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -361,7 +384,7 @@ def test_polymorphism_get_and_put_valid(client): "length": 10.0, "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" + "picture": "//////4=", }, { "fishtype": "goblin", @@ -370,14 +393,15 @@ def test_polymorphism_get_and_put_valid(client): "age": 1, "birthday": "2015-08-08T00:00:00.000Z", "jawsize": 5, - "color": "pinkish-gray" - } + "color": "pinkish-gray", + }, ], "location": "alaska", - "iswild": True + "iswild": True, } client.polymorphism.put_valid(request) + def test_polymorphism_put_valid_missing_required(client): bad_request = { "fishtype": "salmon", @@ -389,33 +413,29 @@ def test_polymorphism_put_valid_missing_required(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "picture": "//////4=" - } + {"fishtype": "sawshark", "species": "dangerous", "length": 10.0, "age": 105, "picture": "//////4="}, ], "location": "alaska", - "iswild": True + "iswild": True, } # in legacy, this raises a ValidationError (when generated with client side validation) with pytest.raises(HttpResponseError) as e: client.polymorphism.put_valid_missing_required(bad_request) assert "Reached server in scenario: /complex/polymorphism/missingrequired/invalid" in str(e.value.response.text()) + # COMPLEX TYPES THAT INVOLVE RECURSIVE REFERENCE + def test_polymorphismrecursive_get_and_put_valid(client): # GET polymorphicrecursive/valid result = client.polymorphicrecursive.get_valid() - assert result['fishtype'] == 'salmon' - assert result['siblings'][0]['fishtype'] == 'shark' - assert result['siblings'][0]['siblings'][0]['fishtype'] == 'salmon' - assert result['siblings'][0]['siblings'][0]['location'] == "atlantic" + assert result["fishtype"] == "salmon" + assert result["siblings"][0]["fishtype"] == "shark" + assert result["siblings"][0]["siblings"][0]["fishtype"] == "salmon" + assert result["siblings"][0]["siblings"][0]["location"] == "atlantic" request = { "fishtype": "salmon", @@ -437,7 +457,7 @@ def test_polymorphismrecursive_get_and_put_valid(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -445,11 +465,11 @@ def test_polymorphismrecursive_get_and_put_valid(client): "length": 10.0, "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } + "picture": "//////4=", + }, ], "location": "atlantic", - "iswild": True + "iswild": True, }, { "fishtype": "sawshark", @@ -458,11 +478,11 @@ def test_polymorphismrecursive_get_and_put_valid(client): "siblings": [], "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } + "picture": "//////4=", + }, ], "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -471,15 +491,16 @@ def test_polymorphismrecursive_get_and_put_valid(client): "siblings": [], "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } + "picture": "//////4=", + }, ], "location": "alaska", - "iswild": True + "iswild": True, } # PUT polymorphicrecursive/valid client.polymorphicrecursive.put_valid(request) + def test_polymorphismrecursive_put_valid_stream(client): path = os.path.abspath( os.path.join( @@ -492,13 +513,16 @@ def test_polymorphismrecursive_put_valid_stream(client): with open(path, "rb") as fd: client.polymorphicrecursive.put_valid(fd) + # Complex types that uses additional properties and polymorphism def test_polymorphism_get_and_put_complicated(client): smart_salmon = client.polymorphism.get_complicated() client.polymorphism.put_complicated(smart_salmon) + # Complex types that uses missing discriminator + def test_polymorphism_get_and_put_missing_discriminator(client): regular_salmon = { "fishtype": "salmon", @@ -510,7 +534,7 @@ def test_polymorphism_get_and_put_missing_discriminator(client): "species": "predator", "length": 20.0, "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" + "birthday": "2012-01-05T01:00:00.000Z", }, { "fishtype": "sawshark", @@ -518,7 +542,7 @@ def test_polymorphism_get_and_put_missing_discriminator(client): "length": 10.0, "age": 105, "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" + "picture": "//////4=", }, { "fishtype": "goblin", @@ -527,33 +551,36 @@ def test_polymorphism_get_and_put_missing_discriminator(client): "age": 1, "birthday": "2015-08-08T00:00:00.000Z", "jawsize": 5, - "color": "pinkish-gray" - } + "color": "pinkish-gray", + }, ], "location": "alaska", - "iswild": True + "iswild": True, } # Not raise is enough of a test client.polymorphism.put_missing_discriminator(regular_salmon) # Dot syntax dot_salmon = client.polymorphism.get_dot_syntax() - assert dot_salmon['fish.type'] == "DotSalmon" - assert dot_salmon['location'] == "sweden" + assert dot_salmon["fish.type"] == "DotSalmon" + assert dot_salmon["location"] == "sweden" + def test_pass_in_api_version(client): assert client._config.api_version == "2016-02-29" with AutoRestComplexTestService(api_version="2021-10-01") as client: assert client._config.api_version == "2021-10-01" + def test_client_api_version(): api_version = "2021-10-01" + def check_api_version(pipeline_request): assert pipeline_request.http_request.query["api-version"] == "2021-10-01" raise ValueError("Succeeded") + client = AutoRestComplexTestService( - api_version=api_version, - policies=[CustomHookPolicy(raw_request_hook=check_api_version)] + api_version=api_version, policies=[CustomHookPolicy(raw_request_hook=check_api_version)] ) # PUT basic/valid diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_config.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_config.py index dadb75ce1da..ce51de4e19d 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_config.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_config.py @@ -26,17 +26,20 @@ from azure.core.pipeline.policies import HttpLoggingPolicy from bodystringversiontolerant import AutoRestSwaggerBATService + def test_http_logging_policy_default(): with AutoRestSwaggerBATService() as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST + def test_http_logging_policy_custom(): http_logging_policy = HttpLoggingPolicy(base_url="test") http_logging_policy = HttpLoggingPolicy() - http_logging_policy.allowed_header_names.update( - {"x-ms-added-header"} - ) + http_logging_policy.allowed_header_names.update({"x-ms-added-header"}) with AutoRestSwaggerBATService(http_logging_policy=http_logging_policy) as client: assert isinstance(client._config.http_logging_policy, HttpLoggingPolicy) - assert client._config.http_logging_policy.allowed_header_names == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + assert ( + client._config.http_logging_policy.allowed_header_names + == HttpLoggingPolicy.DEFAULT_HEADERS_WHITELIST.union({"x-ms-added-header"}) + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_constants.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_constants.py index a71a90ffe58..161c285a0ec 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_constants.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_constants.py @@ -26,24 +26,22 @@ import pytest from constantsversiontolerant import AutoRestSwaggerConstantService + @pytest.fixture def client(): with AutoRestSwaggerConstantService() as client: yield client + def test_put_client_constants(client): client.contants.put_client_constants() assert client._config.header_constant == True assert client._config.query_constant == 100 assert client._config.path_constant == "path" + def test_put_client_constants_override(): - with AutoRestSwaggerConstantService( - header_constant=False, - query_constant=0, - path_constant="new_path" - ) as client: + with AutoRestSwaggerConstantService(header_constant=False, query_constant=0, path_constant="new_path") as client: assert client._config.header_constant == False assert client._config.query_constant == 0 assert client._config.path_constant == "new_path" - \ No newline at end of file diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_custom_base_uri.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_custom_base_uri.py index 35a40190882..40336627098 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_custom_base_uri.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_custom_base_uri.py @@ -29,28 +29,34 @@ from custombaseurlmoreoptionsversiontolerant import AutoRestParameterizedCustomHostTestClient import pytest + @pytest.fixture def client(): - with AutoRestParameterizedHostTestClient("host:3000", retry_total = 0) as client: + with AutoRestParameterizedHostTestClient("host:3000", retry_total=0) as client: yield client + def test_positive(): client = AutoRestParameterizedHostTestClient("host:3000") client.paths.get_empty("local") + def test_get_empty_with_bad_string(client): with pytest.raises(ServiceRequestError): client.paths.get_empty("bad") + def test_get_empty_with_none(client): with pytest.raises(ValueError): client.paths.get_empty(None) + def test_get_empty_from_bad_host(): - with AutoRestParameterizedHostTestClient("badhost:3000", retry_total = 0) as client: + with AutoRestParameterizedHostTestClient("badhost:3000", retry_total=0) as client: with pytest.raises(ServiceRequestError): client.paths.get_empty("local") + def test_more_options(): with AutoRestParameterizedCustomHostTestClient("test12", "host:3000") as client: client.paths.get_empty("http://lo", "cal", "key1") diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_date.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_date.py index 63f00d3c454..457685c8949 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_date.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_date.py @@ -29,32 +29,39 @@ import pytest + @pytest.fixture def client(): with AutoRestDateTestService() as client: yield client + def test_model_get_and_put_max_date(client): max_date = deserialize_date("9999-12-31T23:59:59.999999Z") client.date.put_max_date(str(max_date)) assert max_date == deserialize_date(client.date.get_max_date()) + def test_model_get_and_put_min_date(client): min_date = deserialize_date("0001-01-01T00:00:00Z") client.date.put_min_date(str(min_date)) assert min_date == deserialize_date(client.date.get_min_date()) + def test_model_get_null(client): assert client.date.get_null() is None + def test_model_get_invalid_date(client): assert deserialize_date(client.date.get_invalid_date()) == datetime.date(2001, 1, 1) + def test_model_get_overflow_date(client): with pytest.raises(ValueError) as ex: deserialize_date(client.date.get_overflow_date()) assert "day is out of range for month" in str(ex.value) + def test_model_get_underflow_date(client): with pytest.raises(ValueError) as ex: deserialize_date(client.date.get_underflow_date()) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime.py index 1e19c08ab6b..c65c7605ead 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime.py @@ -29,19 +29,22 @@ import pytest + @pytest.fixture def client(): with AutoRestDateTimeTestService() as client: yield client + def test_utc_max_date_time(client): max_date = deserialize_datetime("9999-12-31T23:59:59.999Z") dt = deserialize_iso(client.datetime.get_utc_lowercase_max_date_time()) - assert dt == max_date + assert dt == max_date dt = deserialize_iso(client.datetime.get_utc_uppercase_max_date_time()) - assert dt == max_date + assert dt == max_date client.datetime.put_utc_max_date_time(serialize_iso(max_date)) + def test_utc_max_date_time_7digits(client): max_date = deserialize_datetime("9999-12-31T23:59:59.999999Z") dt = deserialize_iso(client.datetime.get_utc_uppercase_max_date_time7_digits()) @@ -50,60 +53,76 @@ def test_utc_max_date_time_7digits(client): # Python doesn't support 7 digits client.datetime.put_utc_max_date_time7_digits(max_date) + def test_get_utc_min_date_time(client): min_date = deserialize_datetime("0001-01-01T00:00:00Z") dt = deserialize_iso(client.datetime.get_utc_min_date_time()) - assert dt == min_date + assert dt == min_date client.datetime.put_utc_min_date_time(serialize_iso(min_date)) + def test_get_local_negative_offset_min_date_time(client): client.datetime.get_local_negative_offset_min_date_time() client.datetime.put_local_negative_offset_min_date_time( - serialize_iso(deserialize_datetime("0001-01-01T00:00:00-14:00"))) + serialize_iso(deserialize_datetime("0001-01-01T00:00:00-14:00")) + ) + def test_get_local_no_offset_min_date_time(client): local_no_offset_min_date_time = deserialize_datetime("0001-01-01T00:00:00") dt = deserialize_iso(client.datetime.get_local_no_offset_min_date_time()) assert dt == local_no_offset_min_date_time + def test_get_local_negative_offset_lowercase_max_date_time(client): with pytest.raises(OverflowError): deserialize_iso(client.datetime.get_local_negative_offset_lowercase_max_date_time()) + def test_get_local_negative_offset_uppercase_max_date_time(client): with pytest.raises(OverflowError): deserialize_iso(client.datetime.get_local_negative_offset_uppercase_max_date_time()) + def test_local_positive_offset_min_date_time(client): with pytest.raises(OverflowError): deserialize_iso(client.datetime.get_local_positive_offset_min_date_time()) with pytest.raises(OverflowError): client.datetime.put_local_positive_offset_min_date_time( - serialize_iso(deserialize_datetime("0001-01-01T00:00:00+14:00"))) + serialize_iso(deserialize_datetime("0001-01-01T00:00:00+14:00")) + ) + def test_local_positive_offset_max_date_time(client): client.datetime.get_local_positive_offset_lowercase_max_date_time() client.datetime.get_local_positive_offset_uppercase_max_date_time() client.datetime.put_local_positive_offset_max_date_time( - serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999+14:00"))) + serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999+14:00")) + ) + def test_get_null(client): client.datetime.get_null() + def test_get_overflow(client): with pytest.raises(OverflowError): deserialize_iso(client.datetime.get_overflow()) + def test_get_invalid(client): with pytest.raises(ValueError): deserialize_iso(client.datetime.get_invalid()) + def test_get_underflow(client): with pytest.raises(ValueError): deserialize_iso(client.datetime.get_underflow()) + def test_put_local_negative_offset_max_date_time(client): with pytest.raises(OverflowError): client.datetime.put_local_negative_offset_max_date_time( - serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999-14:00"))) + serialize_iso(deserialize_datetime("9999-12-31T23:59:59.999999-14:00")) + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime_rfc.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime_rfc.py index dda78457019..17b6b137fb9 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime_rfc.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_datetime_rfc.py @@ -30,26 +30,32 @@ import pytest + @pytest.fixture def client(): with AutoRestRFC1123DateTimeTestService() as client: yield client + def test_get_null(client): assert client.datetimerfc1123.get_null() is None + def test_get_invalid(client): with pytest.raises(isodate.ISO8601Error): deserialize_datetime(client.datetimerfc1123.get_invalid()) + def test_get_underflow(client): with pytest.raises(isodate.ISO8601Error): deserialize_datetime(client.datetimerfc1123.get_underflow()) + def test_get_overflow(client): with pytest.raises(isodate.ISO8601Error): deserialize_datetime(client.datetimerfc1123.get_overflow()) + def test_utc_max_date_time(client): max_date = deserialize_datetime("9999-12-31T23:59:59.999999Z") @@ -57,6 +63,7 @@ def test_utc_max_date_time(client): client.datetimerfc1123.get_utc_uppercase_max_date_time() client.datetimerfc1123.put_utc_max_date_time(serialize_rfc(max_date)) + def test_utc_min_date_time(client): min_date = deserialize_datetime("0001-01-01T00:00:00Z") client.datetimerfc1123.get_utc_min_date_time() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_dictionary.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_dictionary.py index 7a8480e86da..96233153b30 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_dictionary.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_dictionary.py @@ -45,17 +45,20 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATDictionaryService() as client: yield client + @pytest.fixture def test_dict(): test_product1 = {"integer": 1, "string": "2"} test_product2 = {"integer": 3, "string": "4"} test_product3 = {"integer": 5, "string": "6"} - return {"0":test_product1, "1":test_product2, "2":test_product3} + return {"0": test_product1, "1": test_product2, "2": test_product3} + @pytest.fixture def get_deserialized_dict(send_request_json_response): @@ -65,259 +68,297 @@ def _get_deserialized_dict(request, deserialize_value_callable): if json_response[key]: json_response[key] = deserialize_value_callable(json_response[key]) return json_response + return _get_deserialized_dict + def get_deserialized_dict(response, deserializer): for key in response: if response[key]: response[key] = deserializer(response[key]) return response + def get_serialized_dict(dict, serializer): - return { - k: serializer(v) for k, v in dict.items() - } + return {k: serializer(v) for k, v in dict.items()} + # Primitive types def test_boolean_tfft(client): - tfft = {"0":True, "1":False, "2":False, "3":True} - assert tfft == client.dictionary.get_boolean_tfft() + tfft = {"0": True, "1": False, "2": False, "3": True} + assert tfft == client.dictionary.get_boolean_tfft() client.dictionary.put_boolean_tfft(tfft) + def test_get_boolean_invalid(client): - invalid_null_dict = {"0":True, "1":None, "2":False} - assert invalid_null_dict == client.dictionary.get_boolean_invalid_null() + invalid_null_dict = {"0": True, "1": None, "2": False} + assert invalid_null_dict == client.dictionary.get_boolean_invalid_null() assert {"0": True, "1": "boolean", "2": False} == client.dictionary.get_boolean_invalid_string() + def test_integer_valid(client): - int_valid = {"0":1, "1":-1, "2":3, "3":300} - assert int_valid == client.dictionary.get_integer_valid() + int_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert int_valid == client.dictionary.get_integer_valid() client.dictionary.put_integer_valid(int_valid) + def test_get_int_invalid(client): - int_null_dict = {"0":1, "1":None, "2":0} - assert int_null_dict == client.dictionary.get_int_invalid_null() + int_null_dict = {"0": 1, "1": None, "2": 0} + assert int_null_dict == client.dictionary.get_int_invalid_null() assert {"0": 1, "1": "integer", "2": 0} == client.dictionary.get_int_invalid_string() + def test_long_valid(client): - long_valid = {"0":1, "1":-1, "2":3, "3":300} - assert long_valid == client.dictionary.get_long_valid() + long_valid = {"0": 1, "1": -1, "2": 3, "3": 300} + assert long_valid == client.dictionary.get_long_valid() client.dictionary.put_long_valid(long_valid) + def test_get_long_invalid(client): - long_null_dict = {"0":1, "1":None, "2":0} - assert long_null_dict == client.dictionary.get_long_invalid_null() + long_null_dict = {"0": 1, "1": None, "2": 0} + assert long_null_dict == client.dictionary.get_long_invalid_null() assert {"0": 1, "1": "integer", "2": 0} == client.dictionary.get_long_invalid_string() + def test_float_valid(client): - float_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert float_valid == client.dictionary.get_float_valid() + float_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert float_valid == client.dictionary.get_float_valid() client.dictionary.put_float_valid(float_valid) + def test_get_float_invalid(client): - float_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert float_null_dict == client.dictionary.get_float_invalid_null() + float_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert float_null_dict == client.dictionary.get_float_invalid_null() assert {"0": 1, "1": "number", "2": 0} == client.dictionary.get_float_invalid_string() + def test_double_valid(client): - double_valid = {"0":0, "1":-0.01, "2":-1.2e20} - assert double_valid == client.dictionary.get_double_valid() + double_valid = {"0": 0, "1": -0.01, "2": -1.2e20} + assert double_valid == client.dictionary.get_double_valid() client.dictionary.put_double_valid(double_valid) + def test_get_double_invalid(client): - double_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - assert double_null_dict == client.dictionary.get_double_invalid_null() + double_null_dict = {"0": 0.0, "1": None, "2": -1.2e20} + assert double_null_dict == client.dictionary.get_double_invalid_null() assert {"0": 1, "1": "number", "2": 0} == client.dictionary.get_double_invalid_string() + def test_string_valid(client): - string_valid = {"0":"foo1", "1":"foo2", "2":"foo3"} - assert string_valid == client.dictionary.get_string_valid() + string_valid = {"0": "foo1", "1": "foo2", "2": "foo3"} + assert string_valid == client.dictionary.get_string_valid() client.dictionary.put_string_valid(string_valid) + def test_get_string_with_null_and_invalid(client): - string_null_dict = {"0":"foo", "1":None, "2":"foo2"} - string_invalid_dict = {"0":"foo", "1":123, "2":"foo2"} # in version-tolerant, we don't know we should serialize this whole thing as string, so serializes 123 as number - assert string_null_dict == client.dictionary.get_string_with_null() - assert string_invalid_dict == client.dictionary.get_string_with_invalid() + string_null_dict = {"0": "foo", "1": None, "2": "foo2"} + string_invalid_dict = { + "0": "foo", + "1": 123, + "2": "foo2", + } # in version-tolerant, we don't know we should serialize this whole thing as string, so serializes 123 as number + assert string_null_dict == client.dictionary.get_string_with_null() + assert string_invalid_dict == client.dictionary.get_string_with_invalid() + def test_date_valid(client): date1 = deserialize_date("2000-12-01T00:00:00Z") date2 = deserialize_date("1980-01-02T00:00:00Z") date3 = deserialize_date("1492-10-12T00:00:00Z") - valid_date_dict = {"0":date1, "1":date2, "2":date3} + valid_date_dict = {"0": date1, "1": date2, "2": date3} date_dictionary = client.dictionary.get_date_valid() assert get_deserialized_dict(date_dictionary, deserialize_date) == valid_date_dict client.dictionary.put_date_valid(get_serialized_dict(valid_date_dict, serialize_date)) + def test_get_date_invalid(client): - date_null_dict = {"0":deserialize_date("2012-01-01"), - "1":None, - "2":deserialize_date("1776-07-04")} + date_null_dict = {"0": deserialize_date("2012-01-01"), "1": None, "2": deserialize_date("1776-07-04")} assert date_null_dict == get_deserialized_dict(client.dictionary.get_date_invalid_null(), deserialize_date) assert {"0": "2011-03-22", "1": "date"} == client.dictionary.get_date_invalid_chars() + def test_date_time_valid(client): datetime1 = deserialize_datetime("2000-12-01T00:00:01Z") datetime2 = deserialize_datetime("1980-01-02T00:11:35+01:00") datetime3 = deserialize_datetime("1492-10-12T10:15:01-08:00") - valid_datetime_dict = {"0":datetime1, "1":datetime2, "2":datetime3} + valid_datetime_dict = {"0": datetime1, "1": datetime2, "2": datetime3} assert valid_datetime_dict == get_deserialized_dict(client.dictionary.get_date_time_valid(), deserialize_iso) client.dictionary.put_date_time_valid(get_serialized_dict(valid_datetime_dict, serialize_iso)) + def test_get_date_time_invalid(client): - datetime_null_dict = {"0":deserialize_datetime("2000-12-01T00:00:01Z"), "1":None} + datetime_null_dict = {"0": deserialize_datetime("2000-12-01T00:00:01Z"), "1": None} assert datetime_null_dict == get_deserialized_dict(client.dictionary.get_date_time_invalid_null(), deserialize_iso) assert {"0": "2000-12-01t00:00:01z", "1": "date-time"} == client.dictionary.get_date_time_invalid_chars() + def test_date_time_rfc1123_valid(client): rfc_datetime1 = deserialize_datetime("2000-12-01T00:00:01Z") rfc_datetime2 = deserialize_datetime("1980-01-02T00:11:35Z") rfc_datetime3 = deserialize_datetime("1492-10-12T10:15:01Z") - valid_rfc_dict = {"0":rfc_datetime1, "1":rfc_datetime2, "2":rfc_datetime3} + valid_rfc_dict = {"0": rfc_datetime1, "1": rfc_datetime2, "2": rfc_datetime3} assert valid_rfc_dict == get_deserialized_dict(client.dictionary.get_date_time_rfc1123_valid(), deserialize_rfc) client.dictionary.put_date_time_rfc1123_valid(get_serialized_dict(valid_rfc_dict, serialize_rfc)) + def test_get_duration_valid(client): duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) duration2 = timedelta(days=5, hours=1) - valid_duration_dict = {"0":duration1, "1":duration2} + valid_duration_dict = {"0": duration1, "1": duration2} assert valid_duration_dict == get_deserialized_dict(client.dictionary.get_duration_valid(), deserialize_duration) client.dictionary.put_duration_valid(get_serialized_dict(valid_duration_dict, serialize_duration)) + def test_bytes_valid(client): bytes1 = bytearray([0x0FF, 0x0FF, 0x0FF, 0x0FA]) bytes2 = bytearray([0x01, 0x02, 0x03]) bytes3 = bytearray([0x025, 0x029, 0x043]) bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_valid = {"0":bytes1, "1":bytes2, "2":bytes3} + bytes_valid = {"0": bytes1, "1": bytes2, "2": bytes3} client.dictionary.put_byte_valid(get_serialized_dict(bytes_valid, serialize_bytearray)) bytes_result = client.dictionary.get_byte_valid() assert bytes_valid == get_deserialized_dict(bytes_result, deserialize_bytearray) + def test_get_byte_invalid_null(client): bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_null = {"0":bytes4, "1":None} + bytes_null = {"0": bytes4, "1": None} bytes_result = get_deserialized_dict(client.dictionary.get_byte_invalid_null(), deserialize_bytearray) - assert bytes_null == bytes_result + assert bytes_null == bytes_result + def test_get_base64_url(client): - test_dict = {'0': 'a string that gets encoded with base64url'.encode(), - '1': 'test string'.encode(), - '2': 'Lorem ipsum'.encode()} - assert get_deserialized_dict(client.dictionary.get_base64_url(), deserialize_base64) == test_dict + test_dict = { + "0": "a string that gets encoded with base64url".encode(), + "1": "test string".encode(), + "2": "Lorem ipsum".encode(), + } + assert get_deserialized_dict(client.dictionary.get_base64_url(), deserialize_base64) == test_dict + # Basic dictionary parsing def test_empty(client): - assert {} == client.dictionary.get_empty() + assert {} == client.dictionary.get_empty() client.dictionary.put_empty({}) + def test_get_null_and_invalid(client): assert client.dictionary.get_null() is None with pytest.raises(DecodeError): client.dictionary.get_invalid() + def test_get_null_key_and_value(client): # {null:"val1"} is not standard JSON format. C# might work and expects this test to pass, # but we fail and we're happy with it. with pytest.raises(DecodeError): client.dictionary.get_null_key() - assert {"key1":None} == client.dictionary.get_null_value() + assert {"key1": None} == client.dictionary.get_null_value() + def test_get_empty_string_key(client): - assert {"":"val1"} == client.dictionary.get_empty_string_key() + assert {"": "val1"} == client.dictionary.get_empty_string_key() + # Dictionary composed types def test_get_complex_null_and_empty(client): assert client.dictionary.get_complex_null() is None - assert {} == client.dictionary.get_complex_empty() + assert {} == client.dictionary.get_complex_empty() + def test_complex_valid(client, test_dict): client.dictionary.put_complex_valid(test_dict) complex_result = client.dictionary.get_complex_valid() - assert test_dict == complex_result + assert test_dict == complex_result + def test_array_valid(client): - list_dict = {"0":["1","2","3"], "1":["4","5","6"], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", "9"]} client.dictionary.put_array_valid(list_dict) array_result = client.dictionary.get_array_valid() - assert list_dict == array_result + assert list_dict == array_result + def test_dictionary_valid(client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{"4":"four","5":"five","6":"six"}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = { + "0": {"1": "one", "2": "two", "3": "three"}, + "1": {"4": "four", "5": "five", "6": "six"}, + "2": {"7": "seven", "8": "eight", "9": "nine"}, + } client.dictionary.put_dictionary_valid(dict_dict) dict_result = client.dictionary.get_dictionary_valid() - assert dict_dict == dict_result + assert dict_dict == dict_result + def test_get_complex_null_and_empty(client): assert client.dictionary.get_complex_null() is None - assert {} == client.dictionary.get_complex_empty() + assert {} == client.dictionary.get_complex_empty() + def test_get_complex_item_null_and_empty(client, test_dict): - test_dict_null = {"0":test_dict["0"], "1":None, "2":test_dict["2"]} + test_dict_null = {"0": test_dict["0"], "1": None, "2": test_dict["2"]} complex_result = client.dictionary.get_complex_item_null() - assert complex_result == test_dict_null + assert complex_result == test_dict_null - test_dict_empty = {"0":test_dict["0"], "1": {}, "2":test_dict["2"]} + test_dict_empty = {"0": test_dict["0"], "1": {}, "2": test_dict["2"]} complex_result = client.dictionary.get_complex_item_empty() - assert complex_result == test_dict_empty + assert complex_result == test_dict_empty + def test_get_array_empty(client): assert client.dictionary.get_array_null() is None - assert {} == client.dictionary.get_array_empty() + assert {} == client.dictionary.get_array_empty() + def test_get_array_item_null_and_empty(client): - list_dict = {"0":["1","2","3"], "1":None, "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": None, "2": ["7", "8", "9"]} array_result = client.dictionary.get_array_item_null() - assert list_dict == array_result + assert list_dict == array_result - list_dict = {"0":["1","2","3"], "1":[], "2":["7","8","9"]} + list_dict = {"0": ["1", "2", "3"], "1": [], "2": ["7", "8", "9"]} array_result = client.dictionary.get_array_item_empty() - assert list_dict == array_result + assert list_dict == array_result + def test_get_dictionary_null_and_empty(client): assert client.dictionary.get_dictionary_null() is None - assert {} == client.dictionary.get_dictionary_empty() + assert {} == client.dictionary.get_dictionary_empty() + def test_get_dictionary_item_null_and_empty(client): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":None, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = {"0": {"1": "one", "2": "two", "3": "three"}, "1": None, "2": {"7": "seven", "8": "eight", "9": "nine"}} dict_result = client.dictionary.get_dictionary_item_null() - assert dict_dict == dict_result + assert dict_dict == dict_result - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{}, - "2":{"7":"seven","8":"eight","9":"nine"}} + dict_dict = {"0": {"1": "one", "2": "two", "3": "three"}, "1": {}, "2": {"7": "seven", "8": "eight", "9": "nine"}} dict_result = client.dictionary.get_dictionary_item_empty() - assert dict_dict == dict_result + assert dict_dict == dict_result diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_duration.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_duration.py index 1cca61b232e..4c9a9ee34fd 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_duration.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_duration.py @@ -31,17 +31,24 @@ import pytest + @pytest.fixture def client(): with AutoRestDurationTestService() as client: yield client + def test_get_null_and_invalid(client): assert client.duration.get_null() is None with pytest.raises(isodate.ISO8601Error): deserialize_duration(client.duration.get_invalid()) + def test_positive_duration(client): - assert isodate.Duration(4, 45005, 0, years=3, months=6) == deserialize_duration(client.duration.get_positive_duration()) - client.duration.put_positive_duration(serialize_duration(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11))) + assert isodate.Duration(4, 45005, 0, years=3, months=6) == deserialize_duration( + client.duration.get_positive_duration() + ) + client.duration.put_positive_duration( + serialize_duration(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_error_with_secrets.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_error_with_secrets.py index fff9a6fe1e0..fe0c4c3780a 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_error_with_secrets.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_error_with_secrets.py @@ -28,6 +28,7 @@ from errorwithsecretsversiontolerant._operations._operations import build_error_with_secrets_create_secret_request from azure.core.exceptions import HttpResponseError + @pytest.fixture def client(): with ErrorWithSecrets() as client: @@ -38,11 +39,12 @@ def test_create_secret(client): request = build_error_with_secrets_create_secret_request( headers={"authorization": "SharedKey 1c88a67921784300a462b2cb61da2339"}, params={"key": "1c88a67921784300a462b2cb61da2339"}, - json={ "key": "1c88a67921784300a462b2cb61da2339" }, + json={"key": "1c88a67921784300a462b2cb61da2339"}, ) response = client.send_request(request) response.raise_for_status() + def test_raise_error_with_secrets(client): with pytest.raises(HttpResponseError) as ex: client.get_error_with_secrets() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_extensible_enums.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_extensible_enums.py index db783e2725d..9446f55096f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_extensible_enums.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_extensible_enums.py @@ -27,35 +27,34 @@ import pytest + @pytest.fixture def client(): with PetStoreInc() as client: yield client + def test_get_by_pet_id(client): # Now enum return are always string (Autorest.Python 3.0) - tommy = client.pet.get_by_pet_id('tommy') - assert tommy["DaysOfWeek"] == "Monday" - assert tommy["IntEnum"] == "1" + tommy = client.pet.get_by_pet_id("tommy") + assert tommy["DaysOfWeek"] == "Monday" + assert tommy["IntEnum"] == "1" - casper = client.pet.get_by_pet_id('casper') - assert casper["DaysOfWeek"] == "Weekend" - assert casper["IntEnum"] == "2" + casper = client.pet.get_by_pet_id("casper") + assert casper["DaysOfWeek"] == "Weekend" + assert casper["IntEnum"] == "2" - scooby = client.pet.get_by_pet_id('scooby') - assert scooby["DaysOfWeek"] == "Thursday" + scooby = client.pet.get_by_pet_id("scooby") + assert scooby["DaysOfWeek"] == "Thursday" # https://github.com/Azure/autorest.csharp/blob/e5f871b7433e0f6ca6a17307fba4a2cfea4942b4/test/vanilla/AcceptanceTests.cs#L429 # "allowedValues" of "x-ms-enum" is not supported in Python - assert scooby["IntEnum"] == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" + assert scooby["IntEnum"] == "2.1" # Might be "2" if one day Python is supposed to support "allowedValues" + def test_add_pet(client): - retriever = { - "name": "Retriever", - "IntEnum": "3", - "DaysOfWeek": "Friday" - } + retriever = {"name": "Retriever", "IntEnum": "3", "DaysOfWeek": "Friday"} returned_pet = client.pet.add_pet(retriever) - assert returned_pet["DaysOfWeek"] == "Friday" - assert returned_pet["IntEnum"] == "3" - assert returned_pet['name'] == "Retriever" + assert returned_pet["DaysOfWeek"] == "Friday" + assert returned_pet["IntEnum"] == "3" + assert returned_pet["name"] == "Retriever" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_file.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_file.py index 1034e15a50e..c9fc4464fd0 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_file.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_file.py @@ -35,11 +35,11 @@ @pytest.fixture def client(connection_data_block_size): - with AutoRestSwaggerBATFileService( - connection_data_block_size=connection_data_block_size) as client: + with AutoRestSwaggerBATFileService(connection_data_block_size=connection_data_block_size) as client: yield client -@pytest.mark.parametrize('connection_data_block_size', [1000]) + +@pytest.mark.parametrize("connection_data_block_size", [1000]) def test_get_file(client): file_length = 0 with io.BytesIO() as file_handle: @@ -50,17 +50,29 @@ def test_get_file(client): file_length += len(data) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) + join( + cwd, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) - with open(sample_file, 'rb') as data: + with open(sample_file, "rb") as data: sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) + assert sample_data == hash(file_handle.getvalue()) + -@pytest.mark.parametrize('connection_data_block_size', [4096]) +@pytest.mark.parametrize("connection_data_block_size", [4096]) def test_get_empty_file(client): file_length = 0 with io.BytesIO() as file_handle: @@ -70,9 +82,10 @@ def test_get_empty_file(client): file_length += len(data) file_handle.write(data) - assert file_length == 0 + assert file_length == 0 + -@pytest.mark.parametrize('connection_data_block_size', [4096]) +@pytest.mark.parametrize("connection_data_block_size", [4096]) def test_files_long_running(client): file_length = 0 stream = client.files.get_file_large() @@ -80,4 +93,4 @@ def test_files_long_running(client): assert 0 < len(data) <= 4096 file_length += len(data) - assert file_length == 3000 * 1024 * 1024 + assert file_length == 3000 * 1024 * 1024 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_form_data.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_form_data.py index 873cd3ff557..d73458d581f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_form_data.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_form_data.py @@ -30,7 +30,7 @@ from os.path import dirname, pardir, join, realpath cwd = dirname(realpath(__file__)) -log_level = int(os.environ.get('PythonLogLevel', 30)) +log_level = int(os.environ.get("PythonLogLevel", 30)) tests = realpath(join(cwd, pardir, "Expected", "AcceptanceTests")) sys.path.append(join(tests, "BodyFormData")) @@ -40,20 +40,22 @@ import pytest + @pytest.fixture def dummy_file(): - with tempfile.NamedTemporaryFile(mode='w', delete=False) as dummy: + with tempfile.NamedTemporaryFile(mode="w", delete=False) as dummy: dummy.write("Test file") # Get outside of the "with", so file can be re-opened on Windows yield dummy.name os.remove(dummy.name) + @pytest.fixture def client(): with AutoRestSwaggerBATFormDataService( - connection_data_block_size = 2, - retry_total = 50, # Be agressive on this test, sometimes testserver DDOS :-p - retry_backoff_factor = 1.6 + connection_data_block_size=2, + retry_total=50, # Be agressive on this test, sometimes testserver DDOS :-p + retry_backoff_factor=1.6, ) as client: yield client @@ -61,17 +63,15 @@ def client(): def test_file_upload_stream(client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: - files = { - "file_content": stream_data, - "file_name": "UploadFile.txt" - } + files = {"file_content": stream_data, "file_name": "UploadFile.txt"} resp = client.formdata.upload_file(files) for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string + def test_file_upload_stream_raw(client): @@ -79,31 +79,27 @@ def test_callback(response, data, headers): return data test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: - files = { - "file_content": stream_data, - "file_name": "UploadFile.txt" - } + files = {"file_content": stream_data, "file_name": "UploadFile.txt"} stream = client.formdata.upload_file(files, cls=test_callback) for data in stream: result.write(data) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string + def test_file_upload_file_stream(client, dummy_file): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - files = { - "file_content": upload_data, - "file_name": name - } + with open(dummy_file, "rb") as upload_data: + files = {"file_content": upload_data, "file_name": name} resp = client.formdata.upload_file(files) for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" + def test_file_upload_file_stream_raw(client, dummy_file): @@ -112,46 +108,45 @@ def test_callback(response, data, headers): name = os.path.basename(dummy_file) result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - files = { - "file_content": upload_data, - "file_name": name - } + with open(dummy_file, "rb") as upload_data: + files = {"file_content": upload_data, "file_name": name} stream = client.formdata.upload_file(files, cls=test_callback) for data in stream: result.write(data) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" + def test_file_body_upload(client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") result = io.BytesIO() with io.BytesIO(test_bytes) as stream_data: resp = client.formdata.upload_file_via_body(stream_data) for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: resp = client.formdata.upload_file_via_body(upload_data) for r in resp: result.write(r) - assert result.getvalue().decode() == "Test file" + assert result.getvalue().decode() == "Test file" + def test_file_body_upload_generator(client, dummy_file): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") def stream_upload(data, length, block_size): progress = 0 while True: block = data.read(block_size) progress += len(block) - print("Progress... {}%".format(int(progress*100/length))) + print("Progress... {}%".format(int(progress * 100 / length))) if not block: break yield block @@ -162,12 +157,12 @@ def stream_upload(data, length, block_size): resp = client.formdata.upload_file_via_body(streamed_upload) for r in resp: result.write(r) - assert result.getvalue().decode() == test_string + assert result.getvalue().decode() == test_string result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: + with open(dummy_file, "rb") as upload_data: streamed_upload = stream_upload(upload_data, len("Test file"), 2) response = client.formdata.upload_file_via_body(streamed_upload) for data in response: result.write(data) - assert result.getvalue().decode() == "Test file" \ No newline at end of file + assert result.getvalue().decode() == "Test file" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_header.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_header.py index f21938472e2..2bc6e60f722 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_header.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_header.py @@ -30,17 +30,21 @@ import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATHeaderService() as client: yield client + @pytest.fixture def value_header(): def _value_header(response, _, headers): return headers.get("value", "") + return _value_header + def test_integer(client, value_header): client.header.param_integer(scenario="positive", value=1) client.header.param_integer(scenario="negative", value=-2) @@ -51,6 +55,7 @@ def test_integer(client, value_header): response = client.header.response_integer(scenario="negative", cls=value_header) assert response == -2 + def test_long(client, value_header): client.header.param_long(scenario="positive", value=105) client.header.param_long(scenario="negative", value=-2) @@ -60,6 +65,7 @@ def test_long(client, value_header): response = client.header.response_long(scenario="negative", cls=value_header) assert response == -2 + def test_float(client, value_header): client.header.param_float(scenario="positive", value=0.07) client.header.param_float(scenario="negative", value=-3.0) @@ -69,6 +75,7 @@ def test_float(client, value_header): response = client.header.response_float(scenario="negative", cls=value_header) assert abs(-3.0 - response) < 0.00001 + def test_double(client, value_header): client.header.param_double(scenario="positive", value=7e120) client.header.param_double(scenario="negative", value=-3.0) @@ -78,6 +85,7 @@ def test_double(client, value_header): response = client.header.response_double(scenario="negative", cls=value_header) assert response == -3.0 + def test_bool(client, value_header): client.header.param_bool(scenario="true", value=True) client.header.param_bool(scenario="false", value=False) @@ -87,6 +95,7 @@ def test_bool(client, value_header): response = client.header.response_bool(scenario="false", cls=value_header) assert response == False + def test_string(client, value_header): client.header.param_string(scenario="valid", value="The quick brown fox jumps over the lazy dog") client.header.param_string(scenario="null", value=None) @@ -99,12 +108,13 @@ def test_string(client, value_header): response = client.header.response_string(scenario="empty", cls=value_header) assert response == "" + def test_enum(client, value_header): - client.header.param_enum(scenario="valid", value='GREY') + client.header.param_enum(scenario="valid", value="GREY") client.header.param_enum(scenario="null", value=None) response = client.header.response_enum(scenario="valid", cls=value_header) - assert response == 'GREY' + assert response == "GREY" # We receive an empty string. # Starting msrest 0.4.22, we consider that if a string is not in the enum, this not @@ -114,6 +124,7 @@ def test_enum(client, value_header): response = client.header.response_enum(scenario="null", cls=value_header) assert response == "" + def test_date(client, value_header): client.header.param_date(scenario="valid", value=isodate.parse_date("2010-01-01")) client.header.param_date(scenario="min", value=datetime.min) @@ -123,6 +134,7 @@ def test_date(client, value_header): response = client.header.response_date(scenario="min", cls=value_header) assert response == isodate.parse_date("0001-01-01") + def test_datetime(client, value_header): client.header.param_datetime(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) client.header.param_datetime(scenario="min", value=datetime.min) @@ -132,6 +144,7 @@ def test_datetime(client, value_header): response = client.header.response_datetime(scenario="min", cls=value_header) assert response == isodate.parse_datetime("0001-01-01T00:00:00Z") + def test_datetime_rfc(client, value_header): client.header.param_datetime_rfc1123(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) client.header.param_datetime_rfc1123(scenario="min", value=datetime.min) @@ -144,14 +157,18 @@ def test_datetime_rfc(client, value_header): response = client.header.response_datetime_rfc1123(scenario="min", cls=value_header) assert response == isodate.parse_datetime("2001-01-01T00:00:00Z") + def test_duration(client, value_header): - client.header.param_duration(scenario="valid", value=timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) + client.header.param_duration( + scenario="valid", value=timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) + ) response = client.header.response_duration(scenario="valid", cls=value_header) assert response == timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) + def test_byte(client, value_header): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") client.header.param_byte(scenario="valid", value=u_bytes) response = client.header.response_byte(scenario="valid", cls=value_header) @@ -159,25 +176,31 @@ def test_byte(client, value_header): client.header.param_existing_key(user_agent_parameter="overwrite") + def test_response_existing_key(client): def useragent_header(response, _, headers): - return headers.get('User-Agent') + return headers.get("User-Agent") + response = client.header.response_existing_key(cls=useragent_header) assert response == "overwrite" + def test_response_protected_key(client): # This test is only valid for C#, which content-type can't be override this way - #client.header.param_protected_key("text/html") + # client.header.param_protected_key("text/html") # This test has different result compare to C#, which content-type is saved in another place. def content_header(response, _, headers): - return headers.get('Content-Type') + return headers.get("Content-Type") + response = client.header.response_protected_key(cls=content_header) assert response == "text/html; charset=utf-8" + def test_custom_request_id(client): def status_code(pipeline_response, _, headers): return pipeline_response.http_response.status_code + custom_headers = {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} response = client.header.custom_request_id(headers=custom_headers, cls=status_code) assert response == 200 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_hooks.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_hooks.py index ec3cef1aa02..91a7dc18ea3 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_hooks.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_hooks.py @@ -27,14 +27,17 @@ from azure.core.pipeline.policies import CustomHookPolicy from bodyarrayversiontolerant import AutoRestSwaggerBATArrayService + def is_rest(obj): return hasattr(obj, "content") + def raw_request_callback(request): assert is_rest(request.http_request) assert hasattr(request.http_request, "set_multipart_mixed") raise ValueError("I entered the callback!") + def test_raw_request_hook(): raw_request_hook_policy = CustomHookPolicy(raw_request_hook=raw_request_callback) client = AutoRestSwaggerBATArrayService(policies=[raw_request_hook_policy]) @@ -42,19 +45,23 @@ def test_raw_request_hook(): client.array.get_array_empty() assert "I entered the callback!" in str(ex.value) + def test_raw_request_hook_send_request(): raw_request_hook_policy = CustomHookPolicy(raw_request_hook=raw_request_callback) client = AutoRestSwaggerBATArrayService(policies=[raw_request_hook_policy]) from bodyarrayversiontolerant.operations._operations import build_array_get_array_empty_request + with pytest.raises(ValueError) as ex: client.send_request(build_array_get_array_empty_request()) assert "I entered the callback!" in str(ex.value) + def raw_response_callback(response): assert is_rest(response.http_response) assert hasattr(response.http_response, "parts") raise ValueError("I entered the callback!") + def test_raw_response_hook(): raw_response_hook_policy = CustomHookPolicy(raw_response_hook=raw_response_callback) client = AutoRestSwaggerBATArrayService(policies=[raw_response_hook_policy]) @@ -62,10 +69,12 @@ def test_raw_response_hook(): client.array.get_array_empty() assert "I entered the callback!" in str(ex.value) + def test_raw_response_hook_send_request(): raw_response_hook_policy = CustomHookPolicy(raw_response_hook=raw_response_callback) client = AutoRestSwaggerBATArrayService(policies=[raw_response_hook_policy]) from bodyarrayversiontolerant.operations._operations import build_array_get_array_empty_request + with pytest.raises(ValueError) as ex: client.send_request(build_array_get_array_empty_request()) assert "I entered the callback!" in str(ex.value) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_http.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_http.py index f625103fc21..3fe87164be6 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_http.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_http.py @@ -39,13 +39,7 @@ @pytest.fixture() def client(cookie_policy): """Create a AutoRestHttpInfrastructureTestService client with test server credentials.""" - policies = [ - HeadersPolicy(), - ContentDecodePolicy(), - RedirectPolicy(), - RetryPolicy(), - cookie_policy - ] + policies = [HeadersPolicy(), ContentDecodePolicy(), RedirectPolicy(), RetryPolicy(), cookie_policy] with AutoRestHttpInfrastructureTestService(policies=policies) as client: yield client @@ -54,10 +48,12 @@ def assert_status(code, func, *args, **kwargs): def return_status(pipeline_response, data, headers): assert isinstance(pipeline_response, PipelineResponse) return pipeline_response.http_response.status_code - kwargs['cls'] = return_status + + kwargs["cls"] = return_status status_code = func(*args, **kwargs) assert status_code == code + def assert_raises_with_message(msg, func, *args, **kwargs): try: func(*args, **kwargs) @@ -66,6 +62,7 @@ def assert_raises_with_message(msg, func, *args, **kwargs): except HttpResponseError as err: assert err.message == msg + def assert_raises_with_model(code, model, func, *args, **kwargs): try: func(*args, **kwargs) @@ -76,6 +73,7 @@ def assert_raises_with_model(code, model, func, *args, **kwargs): assert isinstance(err.model, model) assert err.response.status_code == code + def assert_raises_with_status(code, func, *args, **kwargs): try: func(*args, **kwargs) @@ -85,6 +83,7 @@ def assert_raises_with_status(code, func, *args, **kwargs): assert err.response.status_code == code + def assert_raises_with_status_and_message(status_code, message, func, *args, **kwargs): try: func(*args, **kwargs) @@ -92,7 +91,8 @@ def assert_raises_with_status_and_message(status_code, message, func, *args, **k except HttpResponseError as err: assert err.status_code == status_code - assert err.response.json()['message'] == message + assert err.response.json()["message"] == message + def assert_raises_with_status_and_response_contains(code, msg, func, *args, **kwargs): try: @@ -103,62 +103,66 @@ def assert_raises_with_status_and_response_contains(code, msg, func, *args, **kw assert err.response.status_code == code assert msg in err.response.text() + def test_get200_model204(client): r = client.multiple_responses.get200_model204_no_model_default_error200_valid() - assert '200' == r['statusCode'] + assert "200" == r["statusCode"] - assert_raises_with_status(201, - client.multiple_responses.get200_model204_no_model_default_error201_invalid) + assert_raises_with_status(201, client.multiple_responses.get200_model204_no_model_default_error201_invalid) - assert_raises_with_status(202, - client.multiple_responses.get200_model204_no_model_default_error202_none) + assert_raises_with_status(202, client.multiple_responses.get200_model204_no_model_default_error202_none) assert client.multiple_responses.get200_model204_no_model_default_error204_valid() is None - assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model204_no_model_default_error400_valid) + assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model204_no_model_default_error400_valid + ) + def test_get200_model201(client): assert_status(200, client.multiple_responses.get200_model201_model_default_error200_valid) b_model = client.multiple_responses.get200_model201_model_default_error201_valid() assert b_model is not None - assert b_model['statusCode'] == "201" - assert b_model['textStatusCode'] == "Created" + assert b_model["statusCode"] == "201" + assert b_model["textStatusCode"] == "Created" + + assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model201_model_default_error400_valid + ) - assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model201_model_default_error400_valid) def test_get200_model_a201_model_c404(client): a_model = client.multiple_responses.get200_model_a201_model_c404_model_d_default_error200_valid() assert a_model is not None - assert a_model['statusCode'] == "200" + assert a_model["statusCode"] == "200" c_model = client.multiple_responses.get200_model_a201_model_c404_model_d_default_error201_valid() assert c_model is not None - assert c_model['httpCode'] == "201" + assert c_model["httpCode"] == "201" - assert_status(404, - client.multiple_responses.get200_model_a201_model_c404_model_d_default_error404_valid) + assert_status(404, client.multiple_responses.get200_model_a201_model_c404_model_d_default_error404_valid) + + assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid + ) - assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get200_model_a201_model_c404_model_d_default_error400_valid) def test_get202_none204(client): client.multiple_responses.get202_none204_none_default_error202_none() client.multiple_responses.get202_none204_none_default_error204_none() - assert_raises_with_status_and_message(400, "client error", - client.multiple_responses.get202_none204_none_default_error400_valid) + assert_raises_with_status_and_message( + 400, "client error", client.multiple_responses.get202_none204_none_default_error400_valid + ) client.multiple_responses.get202_none204_none_default_none202_invalid() client.multiple_responses.get202_none204_none_default_none204_none() - assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_none) + assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_none) + + assert_raises_with_status(400, client.multiple_responses.get202_none204_none_default_none400_invalid) - assert_raises_with_status(400, - client.multiple_responses.get202_none204_none_default_none400_invalid) def test_get_default_model_a200(client): assert_status(200, client.multiple_responses.get_default_model_a200_valid) @@ -167,187 +171,183 @@ def test_get_default_model_a200(client): client.multiple_responses.get_default_model_a200_valid() client.multiple_responses.get_default_model_a200_none() + @pytest.mark.skip(reason="Not generating with models yet") def test_get_default_model_a400(client): - assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_valid) + assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_valid) + + assert_raises_with_model(400, MyException, client.multiple_responses.get_default_model_a400_none) - assert_raises_with_model(400, MyException, - client.multiple_responses.get_default_model_a400_none) def test_get_default_none200(client): client.multiple_responses.get_default_none200_invalid() client.multiple_responses.get_default_none200_none() + def test_get_default_none400(client): - assert_raises_with_status(400, - client.multiple_responses.get_default_none400_invalid) + assert_raises_with_status(400, client.multiple_responses.get_default_none400_invalid) + + assert_raises_with_status(400, client.multiple_responses.get_default_none400_none) - assert_raises_with_status(400, - client.multiple_responses.get_default_none400_none) def test_get200_model_a200(client): assert client.multiple_responses.get200_model_a200_none() is None assert_status(200, client.multiple_responses.get200_model_a200_valid) - assert_status(200, client.multiple_responses.get200_model_a200_invalid) # in legacy it's supposed to deserialized as exception model "MyException" + assert_status( + 200, client.multiple_responses.get200_model_a200_invalid + ) # in legacy it's supposed to deserialized as exception model "MyException" + def test_get200_model_a400(client): - assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_none) - assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_valid) - assert_raises_with_status(400, - client.multiple_responses.get200_model_a400_invalid) + assert_raises_with_status(400, client.multiple_responses.get200_model_a400_none) + assert_raises_with_status(400, client.multiple_responses.get200_model_a400_valid) + assert_raises_with_status(400, client.multiple_responses.get200_model_a400_invalid) + def test_get200_model_a202(client): - assert_raises_with_status(202, - client.multiple_responses.get200_model_a202_valid) + assert_raises_with_status(202, client.multiple_responses.get200_model_a202_valid) + def test_server_error_status_codes_501(client): - assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.head501) + assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.head501) + + assert_raises_with_status(requests.codes.not_implemented, client.http_server_failure.get501) - assert_raises_with_status(requests.codes.not_implemented, - client.http_server_failure.get501) def test_server_error_status_codes_505(client): - assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.post505) + assert_raises_with_status(requests.codes.http_version_not_supported, client.http_server_failure.post505) + + assert_raises_with_status(requests.codes.http_version_not_supported, client.http_server_failure.delete505) - assert_raises_with_status(requests.codes.http_version_not_supported, - client.http_server_failure.delete505) def test_retry_status_codes_408(client): client.http_retry.head408() + def test_retry_status_codes_502(client): client.http_retry.get502() client.http_retry.options502() + def test_retry_status_codes_500(client): client.http_retry.put500() client.http_retry.patch500() + def test_retry_status_codes_503(client): client.http_retry.post503() client.http_retry.delete503() + def test_retry_status_codes_504(client): client.http_retry.put504() client.http_retry.patch504() + def test_error_status_codes_400(client): - assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.head400) + assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.head400) - assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.get400) + assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.get400) # TODO, 4042586: Support options operations in swagger modeler - #assert_raises_with_status(requests.codes.bad_request, + # assert_raises_with_status(requests.codes.bad_request, # client.http_client_failure.options400) - assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.put400) + assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.put400) + + assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.patch400) - assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.patch400) + assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.post400) - assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.post400) + assert_raises_with_status(requests.codes.bad_request, client.http_client_failure.delete400) - assert_raises_with_status(requests.codes.bad_request, - client.http_client_failure.delete400) def test_error_status_codes_401(client): - assert_raises_with_status(requests.codes.unauthorized, - client.http_client_failure.head401) + assert_raises_with_status(requests.codes.unauthorized, client.http_client_failure.head401) + def test_error_status_codes_402(client): - assert_raises_with_status(requests.codes.payment_required, - client.http_client_failure.get402) + assert_raises_with_status(requests.codes.payment_required, client.http_client_failure.get402) + def test_error_status_codes_403(client): # TODO, 4042586: Support options operations in swagger modeler - #assert_raises_with_status(requests.codes.forbidden, + # assert_raises_with_status(requests.codes.forbidden, # client.http_client_failure.options403) - assert_raises_with_status(requests.codes.forbidden, - client.http_client_failure.get403) + assert_raises_with_status(requests.codes.forbidden, client.http_client_failure.get403) + def test_error_status_codes_404(client): - assert_raises_with_status(requests.codes.not_found, - client.http_client_failure.put404) + assert_raises_with_status(requests.codes.not_found, client.http_client_failure.put404) + def test_error_status_codes_405(client): - assert_raises_with_status(requests.codes.method_not_allowed, - client.http_client_failure.patch405) + assert_raises_with_status(requests.codes.method_not_allowed, client.http_client_failure.patch405) + def test_error_status_codes_406(client): - assert_raises_with_status(requests.codes.not_acceptable, - client.http_client_failure.post406) + assert_raises_with_status(requests.codes.not_acceptable, client.http_client_failure.post406) + def test_error_status_codes_407(client): - assert_raises_with_status(requests.codes.proxy_authentication_required, - client.http_client_failure.delete407) + assert_raises_with_status(requests.codes.proxy_authentication_required, client.http_client_failure.delete407) + def test_error_status_codes_409(client): - assert_raises_with_status(requests.codes.conflict, - client.http_client_failure.put409) + assert_raises_with_status(requests.codes.conflict, client.http_client_failure.put409) + def test_error_status_codes_410(client): - assert_raises_with_status(requests.codes.gone, - client.http_client_failure.head410) + assert_raises_with_status(requests.codes.gone, client.http_client_failure.head410) + def test_error_status_codes_411(client): - assert_raises_with_status(requests.codes.length_required, - client.http_client_failure.get411) + assert_raises_with_status(requests.codes.length_required, client.http_client_failure.get411) # TODO, 4042586: Support options operations in swagger modeler - #assert_raises_with_status(requests.codes.precondition_failed, + # assert_raises_with_status(requests.codes.precondition_failed, # client.http_client_failure.options412) - assert_raises_with_status(requests.codes.precondition_failed, - client.http_client_failure.get412) + assert_raises_with_status(requests.codes.precondition_failed, client.http_client_failure.get412) + + assert_raises_with_status(requests.codes.request_entity_too_large, client.http_client_failure.put413) - assert_raises_with_status(requests.codes.request_entity_too_large, - client.http_client_failure.put413) + assert_raises_with_status(requests.codes.request_uri_too_large, client.http_client_failure.patch414) - assert_raises_with_status(requests.codes.request_uri_too_large, - client.http_client_failure.patch414) + assert_raises_with_status(requests.codes.unsupported_media, client.http_client_failure.post415) - assert_raises_with_status(requests.codes.unsupported_media, - client.http_client_failure.post415) + assert_raises_with_status(requests.codes.requested_range_not_satisfiable, client.http_client_failure.get416) - assert_raises_with_status(requests.codes.requested_range_not_satisfiable, - client.http_client_failure.get416) + assert_raises_with_status(requests.codes.expectation_failed, client.http_client_failure.delete417) - assert_raises_with_status(requests.codes.expectation_failed, - client.http_client_failure.delete417) + assert_raises_with_status(429, client.http_client_failure.head429) - assert_raises_with_status(429, - client.http_client_failure.head429) def test_redirect_to_300(client): assert_status(200, client.http_redirects.get300) assert_status(200, client.http_redirects.head300) + def test_redirect_to_301(client): assert_status(200, client.http_redirects.head301) assert_status(200, client.http_redirects.get301) assert_status(requests.codes.moved_permanently, client.http_redirects.put301) + def test_redirect_to_302(client): assert_status(200, client.http_redirects.head302) assert_status(200, client.http_redirects.get302) assert_status(requests.codes.found, client.http_redirects.patch302) + def test_redicret_to_303(client): assert_status(200, client.http_redirects.post303) + def test_redirect_to_307(client): assert_status(200, client.http_redirects.head307) assert_status(200, client.http_redirects.get307) @@ -358,14 +358,17 @@ def test_redirect_to_307(client): assert_status(200, client.http_redirects.delete307) - def test_bad_request_status_assert(client): - assert_raises_with_message("Operation returned an invalid status 'Bad Request'", - client.http_failure.get_empty_error) + assert_raises_with_message( + "Operation returned an invalid status 'Bad Request'", client.http_failure.get_empty_error + ) + def test_no_error_model_status_assert(client): - assert_raises_with_status_and_response_contains(requests.codes.bad_request, "NoErrorModel", - client.http_failure.get_no_model_error) + assert_raises_with_status_and_response_contains( + requests.codes.bad_request, "NoErrorModel", client.http_failure.get_no_model_error + ) + def test_success_status_codes_200(client): client.http_success.head200() @@ -376,18 +379,21 @@ def test_success_status_codes_200(client): client.http_success.delete200() # TODO, 4042586: Support options operations in swagger modeler - #assert client.http_success.options200() + # assert client.http_success.options200() + def test_success_status_codes_201(client): client.http_success.put201() client.http_success.post201() + def test_success_status_codes_202(client): client.http_success.put202() client.http_success.post202() client.http_success.patch202() client.http_success.delete202() + def test_success_status_codes_204(client): client.http_success.head204() client.http_success.put204() @@ -395,9 +401,10 @@ def test_success_status_codes_204(client): client.http_success.delete204() client.http_success.patch204() + def test_success_status_codes_404(client): client.http_success.head404() + def test_empty_no_content(client): - assert_raises_with_status(requests.codes.bad_request, - client.http_failure.get_no_model_empty) + assert_raises_with_status(requests.codes.bad_request, client.http_failure.get_no_model_empty) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_incorrect_error_response.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_incorrect_error_response.py index 002a2732bb2..babdf2ab619 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_incorrect_error_response.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_incorrect_error_response.py @@ -27,8 +27,9 @@ from azure.core.exceptions import HttpResponseError from incorrecterrorresponseversiontolerant import IncorrectReturnedErrorModel + @pytest.mark.skip(reason="Not deserializing models yet") def test_swallow_deserialization_error_for_error_model(): client = IncorrectReturnedErrorModel() with pytest.raises(HttpResponseError): - client.get_incorrect_error_from_server() \ No newline at end of file + client.get_incorrect_error_from_server() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_inputs.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_inputs.py index 416a96c92d5..6021e52fba2 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_inputs.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_inputs.py @@ -26,39 +26,47 @@ import pytest from bodycomplexversiontolerant import AutoRestComplexTestService from azure.core.pipeline.policies import CustomHookPolicy + try: from urlparse import urlparse # type: ignore except ImportError: from urllib.parse import urlparse + def get_client(callback): return AutoRestComplexTestService(policies=[CustomHookPolicy(raw_request_hook=callback)]) + def test_header_input(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 2 assert pipeline_request.http_request.headers["hello"] == "world!" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: client.basic.get_empty(headers={"hello": "world!"}) assert str(ex.value) == "Passed!" + def test_header_input_override(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 1 assert pipeline_request.http_request.headers["Accept"] == "my/content-type" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: client.basic.get_empty(headers={"Accept": "my/content-type"}) assert str(ex.value) == "Passed!" + def test_header_none_input(): with AutoRestComplexTestService() as client: client.basic.get_empty(headers=None) + def test_header_case_insensitive(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 1 @@ -72,26 +80,31 @@ def get_headers(pipeline_request): client.basic.get_empty(headers={accept_key: "my/content-type"}) assert str(ex.value) == "Passed!" + def test_header_kwarg_and_header(): def get_headers(pipeline_request): assert len(pipeline_request.http_request.headers) == 2 assert pipeline_request.http_request.headers["content-type"] == "my/json" assert pipeline_request.http_request.headers["accept"] == "application/json" raise ValueError("Passed!") + client = get_client(callback=get_headers) with pytest.raises(ValueError) as ex: client.basic.put_valid(None, headers={"content-type": "shouldn't/be-me"}, content_type="my/json") assert str(ex.value) == "Passed!" + def test_query_input(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "foo=bar" raise ValueError("Passed!") + client = get_client(callback=get_query) with pytest.raises(ValueError) as ex: client.basic.get_empty(params={"foo": "bar"}) assert str(ex.value) == "Passed!" + def test_query_input_override(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "new-api-version=2021-10-01&api-version=2016-02-29" @@ -105,10 +118,12 @@ def get_query(pipeline_request): assert str(ex.value) == "Passed!" + def test_query_none_input(): with AutoRestComplexTestService() as client: client.basic.get_empty(params=None) + def test_query_case_insensitive(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query.lower() == "foo=bar" @@ -121,6 +136,7 @@ def get_query(pipeline_request): client.basic.get_empty(params={query_key: "bar"}) assert str(ex.value) == "Passed!" + def test_query_kwarg_and_header(): def get_query(pipeline_request): assert urlparse(pipeline_request.http_request.url).query == "api-version=2016-02-29" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_integer.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_integer.py index c40091c0b89..7dc2a61a95a 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_integer.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_integer.py @@ -31,39 +31,47 @@ import pytest + @pytest.fixture def client(): with AutoRestIntegerTestService() as client: yield client + def test_max_min_32_bit(client): - client.int_operations.put_max32(2147483647) # sys.maxint + client.int_operations.put_max32(2147483647) # sys.maxint client.int_operations.put_min32(-2147483648) + def test_max_min_64_bit(client): client.int_operations.put_max64(9223372036854776000) # sys.maxsize client.int_operations.put_min64(-9223372036854776000) + def test_get_null_and_invalid(client): client.int_operations.get_null() with pytest.raises(DecodeError): client.int_operations.get_invalid() + def test_get_overflow(client): # Testserver excepts these to fail, but they won't in Python and it's ok. client.int_operations.get_overflow_int32() client.int_operations.get_overflow_int64() + def test_get_underflow(client): client.int_operations.get_underflow_int32() client.int_operations.get_underflow_int64() + def test_unix_time_date(client): unix_date = datetime(year=2016, month=4, day=13) client.int_operations.put_unix_time_date(serialize_unix(unix_date)) assert unix_date.utctimetuple() == deserialize_unix(client.int_operations.get_unix_time()).utctimetuple() + def test_get_null_and_invalid_unix_time(client): assert client.int_operations.get_null_unix_time() is None diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_media_types.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_media_types.py index f82c00a237e..a2c325acb38 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_media_types.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_media_types.py @@ -28,42 +28,50 @@ import pytest import json + @pytest.fixture def client(): with MediaTypesClient() as client: yield client + def test_pdf(client): result = client.analyze_body(input=b"PDF", content_type="application/pdf") assert result == "Nice job with PDF" with pytest.raises(TypeError): client.analyze_body(input=b"PDF") + def test_json(client): json_input = json.loads('{"source":"foo"}') result = client.analyze_body(input=json_input) assert result == "Nice job with JSON" + def test_content_type_with_encoding(client): - result = client.content_type_with_encoding(input="hello", content_type='text/plain; charset=UTF-8') + result = client.content_type_with_encoding(input="hello", content_type="text/plain; charset=UTF-8") assert result == "Nice job sending content type with encoding" + def test_pdf_no_accept_header(client): client.analyze_body_no_accept_header(input=b"PDF", content_type="application/pdf") + def test_json_no_accept_header(client): json_input = json.loads('{"source":"foo"}') client.analyze_body_no_accept_header(input=json_input) + def test_binary_body_two_content_types(client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} client.binary_body_with_two_content_types(json.dumps(json_input), content_type="application/json") content = b"hello, world" client.binary_body_with_two_content_types(content, content_type="application/octet-stream") + def test_binary_body_three_content_types(client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} client.binary_body_with_three_content_types(json.dumps(json_input), content_type="application/json") content = b"hello, world" @@ -72,8 +80,9 @@ def test_binary_body_three_content_types(client): content = "hello, world" client.binary_body_with_three_content_types(content, content_type="text/plain") + def test_body_three_types(client): - json_input = {"hello":"world"} + json_input = {"hello": "world"} client.body_three_types(json_input) content = b"hello, world" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_merge_patch_json.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_merge_patch_json.py index 925eceac5a6..122d9f4a066 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_merge_patch_json.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_merge_patch_json.py @@ -27,10 +27,12 @@ import pytest + @pytest.fixture def client(): with MergePatchJsonClient() as client: yield client + def test_merge_patch_json(client): client.patch_single({"foo": "bar"}) == "Success!" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_model_flattening.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_model_flattening.py index 93b638148d7..128649a9609 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_model_flattening.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_model_flattening.py @@ -27,196 +27,152 @@ from modelflatteningversiontolerant import AutoRestResourceFlatteningTestService import pytest + @pytest.fixture() def client(): with AutoRestResourceFlatteningTestService() as client: yield client + + def test_flattening_array(client): - #Array + # Array result = client.get_array() - assert 3 == len(result) + assert 3 == len(result) # Resource 1 - assert "1" == result[0]['id'] - assert "OK" == result[0]['properties']['provisioningStateValues'] - assert "Product1" == result[0]['properties']['p.name'] - assert "Flat" == result[0]['properties']['type'] - assert "Building 44" == result[0]['location'] - assert "Resource1" == result[0]['name'] - assert "Succeeded" == result[0]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result[0]['type'] - assert "value1" == result[0]['tags']["tag1"] - assert "value3" == result[0]['tags']["tag2"] + assert "1" == result[0]["id"] + assert "OK" == result[0]["properties"]["provisioningStateValues"] + assert "Product1" == result[0]["properties"]["p.name"] + assert "Flat" == result[0]["properties"]["type"] + assert "Building 44" == result[0]["location"] + assert "Resource1" == result[0]["name"] + assert "Succeeded" == result[0]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result[0]["type"] + assert "value1" == result[0]["tags"]["tag1"] + assert "value3" == result[0]["tags"]["tag2"] # Resource 2 - assert "2" == result[1]['id'] - assert "Resource2" == result[1]['name'] - assert "Building 44" == result[1]['location'] + assert "2" == result[1]["id"] + assert "Resource2" == result[1]["name"] + assert "Building 44" == result[1]["location"] # Resource 3 - assert "3" == result[2]['id'] - assert "Resource3" == result[2]['name'] + assert "3" == result[2]["id"] + assert "Resource3" == result[2]["name"] resource_array = [ - { - 'tags': { - 'tag1': 'value1', - 'tag2': 'value3' - }, - 'location': 'West US' - }, - { - 'location': 'Building 44' - } + {"tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US"}, + {"location": "Building 44"}, ] client.put_array(resource_array) + def test_flattening_dictionary(client): - #Dictionary + # Dictionary result = client.get_dictionary() - assert 3 == len(result) + assert 3 == len(result) # Resource 1 - assert "1" == result["Product1"]['id'] - assert "OK" == result["Product1"]['properties']['provisioningStateValues'] - assert "Product1" == result["Product1"]['properties']['p.name'] - assert "Flat" == result["Product1"]['properties']['type'] - assert "Building 44" == result["Product1"]['location'] - assert "Resource1" == result["Product1"]['name'] - assert "Succeeded" == result["Product1"]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result["Product1"]['type'] - assert "value1" == result["Product1"]['tags']["tag1"] - assert "value3" == result["Product1"]['tags']["tag2"] + assert "1" == result["Product1"]["id"] + assert "OK" == result["Product1"]["properties"]["provisioningStateValues"] + assert "Product1" == result["Product1"]["properties"]["p.name"] + assert "Flat" == result["Product1"]["properties"]["type"] + assert "Building 44" == result["Product1"]["location"] + assert "Resource1" == result["Product1"]["name"] + assert "Succeeded" == result["Product1"]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result["Product1"]["type"] + assert "value1" == result["Product1"]["tags"]["tag1"] + assert "value3" == result["Product1"]["tags"]["tag2"] # Resource 2 - assert "2" == result["Product2"]['id'] - assert "Resource2" == result["Product2"]['name'] - assert "Building 44" == result["Product2"]['location'] + assert "2" == result["Product2"]["id"] + assert "Resource2" == result["Product2"]["name"] + assert "Building 44" == result["Product2"]["location"] # Resource 3 - assert "3" == result["Product3"]['id'] - assert "Resource3" == result["Product3"]['name'] + assert "3" == result["Product3"]["id"] + assert "Resource3" == result["Product3"]["name"] resource_dictionary = { "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, + "tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } + "properties": {"p.name": "Product1", "type": "Flat"}, }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } + "Resource2": {"location": "Building 44", "properties": {"p.name": "Product2", "type": "Flat"}}, } client.put_dictionary(resource_dictionary) + def test_flattening_complex_object(client): - #ResourceCollection + # ResourceCollection result = client.get_resource_collection() - #dictionaryofresources - assert 3 == len(result['dictionaryofresources']) + # dictionaryofresources + assert 3 == len(result["dictionaryofresources"]) # Resource 1 - assert "1" == result['dictionaryofresources']["Product1"]['id'] - assert "OK" == result['dictionaryofresources']["Product1"]['properties']['provisioningStateValues'] - assert "Product1" == result['dictionaryofresources']["Product1"]['properties']['p.name'] - assert "Flat" == result['dictionaryofresources']["Product1"]['properties']['type'] - assert "Building 44" == result['dictionaryofresources']["Product1"]['location'] - assert "Resource1" == result['dictionaryofresources']["Product1"]['name'] - assert "Succeeded" == result['dictionaryofresources']["Product1"]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result['dictionaryofresources']["Product1"]['type'] - assert "value1" == result['dictionaryofresources']["Product1"]['tags']["tag1"] - assert "value3" == result['dictionaryofresources']["Product1"]['tags']["tag2"] + assert "1" == result["dictionaryofresources"]["Product1"]["id"] + assert "OK" == result["dictionaryofresources"]["Product1"]["properties"]["provisioningStateValues"] + assert "Product1" == result["dictionaryofresources"]["Product1"]["properties"]["p.name"] + assert "Flat" == result["dictionaryofresources"]["Product1"]["properties"]["type"] + assert "Building 44" == result["dictionaryofresources"]["Product1"]["location"] + assert "Resource1" == result["dictionaryofresources"]["Product1"]["name"] + assert "Succeeded" == result["dictionaryofresources"]["Product1"]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result["dictionaryofresources"]["Product1"]["type"] + assert "value1" == result["dictionaryofresources"]["Product1"]["tags"]["tag1"] + assert "value3" == result["dictionaryofresources"]["Product1"]["tags"]["tag2"] # Resource 2 - assert "2" == result['dictionaryofresources']["Product2"]['id'] - assert "Resource2" == result['dictionaryofresources']["Product2"]['name'] - assert "Building 44" == result['dictionaryofresources']["Product2"]['location'] + assert "2" == result["dictionaryofresources"]["Product2"]["id"] + assert "Resource2" == result["dictionaryofresources"]["Product2"]["name"] + assert "Building 44" == result["dictionaryofresources"]["Product2"]["location"] # Resource 3 - assert "3" == result['dictionaryofresources']["Product3"]['id'] - assert "Resource3" == result['dictionaryofresources']["Product3"]['name'] + assert "3" == result["dictionaryofresources"]["Product3"]["id"] + assert "Resource3" == result["dictionaryofresources"]["Product3"]["name"] - #arrayofresources - assert 3 == len(result['arrayofresources']) + # arrayofresources + assert 3 == len(result["arrayofresources"]) # Resource 1 - assert "4" == result['arrayofresources'][0]['id'] - assert "OK" == result['arrayofresources'][0]['properties']['provisioningStateValues'] - assert "Product4" == result['arrayofresources'][0]['properties']['p.name'] - assert "Flat" == result['arrayofresources'][0]['properties']['type'] - assert "Building 44" == result['arrayofresources'][0]['location'] - assert "Resource4" == result['arrayofresources'][0]['name'] - assert "Succeeded" == result['arrayofresources'][0]['properties']['provisioningState'] - assert "Microsoft.Web/sites" == result['arrayofresources'][0]['type'] - assert "value1" == result['arrayofresources'][0]['tags']["tag1"] - assert "value3" == result['arrayofresources'][0]['tags']["tag2"] + assert "4" == result["arrayofresources"][0]["id"] + assert "OK" == result["arrayofresources"][0]["properties"]["provisioningStateValues"] + assert "Product4" == result["arrayofresources"][0]["properties"]["p.name"] + assert "Flat" == result["arrayofresources"][0]["properties"]["type"] + assert "Building 44" == result["arrayofresources"][0]["location"] + assert "Resource4" == result["arrayofresources"][0]["name"] + assert "Succeeded" == result["arrayofresources"][0]["properties"]["provisioningState"] + assert "Microsoft.Web/sites" == result["arrayofresources"][0]["type"] + assert "value1" == result["arrayofresources"][0]["tags"]["tag1"] + assert "value3" == result["arrayofresources"][0]["tags"]["tag2"] # Resource 2 - assert "5" == result['arrayofresources'][1]['id'] - assert "Resource5" == result['arrayofresources'][1]['name'] - assert "Building 44" == result['arrayofresources'][1]['location'] + assert "5" == result["arrayofresources"][1]["id"] + assert "Resource5" == result["arrayofresources"][1]["name"] + assert "Building 44" == result["arrayofresources"][1]["location"] # Resource 3 - assert "6" == result['arrayofresources'][2]['id'] - assert "Resource6" == result['arrayofresources'][2]['name'] + assert "6" == result["arrayofresources"][2]["id"] + assert "Resource6" == result["arrayofresources"][2]["name"] - #productresource - assert "7" == result['productresource']['id'] - assert "Resource7" == result['productresource']['name'] + # productresource + assert "7" == result["productresource"]["id"] + assert "Resource7" == result["productresource"]["name"] resource_dictionary = { - "productresource": { - "location": "India", - "properties": { - "p.name": "Azure", - "type": "Flat" - } - }, + "productresource": {"location": "India", "properties": {"p.name": "Azure", "type": "Flat"}}, "arrayofresources": [ { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, + "tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } + "properties": {"p.name": "Product1", "type": "Flat"}, }, - { - "location": "East US", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } + {"location": "East US", "properties": {"p.name": "Product2", "type": "Flat"}}, ], "dictionaryofresources": { "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, + "tags": {"tag1": "value1", "tag2": "value3"}, "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } + "properties": {"p.name": "Product1", "type": "Flat"}, }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - } + "Resource2": {"location": "Building 44", "properties": {"p.name": "Product2", "type": "Flat"}}, + }, } client.put_resource_collection(resource_dictionary) + def test_model_flattening_simple(client): simple_product = { @@ -225,14 +181,12 @@ def test_model_flattening_simple(client): "details": { "max_product_display_name": "max name", "max_product_capacity": "Large", - "max_product_image": { - "generic_value": "https://generic", - "@odata.value": "http://foo" - } - } + "max_product_image": {"generic_value": "https://generic", "@odata.value": "http://foo"}, + }, } result = client.put_simple_product(simple_product) - assert result == simple_product + assert result == simple_product + def test_model_flattening_with_parameter_flattening(client): @@ -242,14 +196,13 @@ def test_model_flattening_with_parameter_flattening(client): "details": { "max_product_display_name": "max name", "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } + "max_product_image": {"@odata.value": "http://foo"}, + }, } result = client.post_flattened_simple_product(simple_product) assert result == simple_product + def test_model_flattening_with_grouping(client): simple_product = { "base_product_id": "123", @@ -257,10 +210,8 @@ def test_model_flattening_with_grouping(client): "details": { "max_product_display_name": "max name", "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } + "max_product_image": {"@odata.value": "http://foo"}, + }, } - result = client.put_simple_product_with_grouping('groupproduct', simple_product) + result = client.put_simple_product_with_grouping("groupproduct", simple_product) assert result == simple_product diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_multiple_inheritance.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_multiple_inheritance.py index 259ff9e9333..96792d5157d 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_multiple_inheritance.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_multiple_inheritance.py @@ -27,42 +27,61 @@ from multipleinheritanceversiontolerant import MultipleInheritanceServiceClient import pytest + @pytest.fixture def client(): with MultipleInheritanceServiceClient() as client: yield client + def test_get_pet(client): assert {"name": "Peanut"} == client.get_pet() + def test_put_pet(client): result = client.put_pet({"name": "Butter"}) assert result == "Pet was correct!" + def test_get_horse(client): assert {"name": "Fred", "isAShowHorse": True} == client.get_horse() + def test_put_horse(client): result = client.put_horse({"name": "General", "isAShowHorse": False}) assert result == "Horse was correct!" + def test_get_feline(client): assert {"meows": True, "hisses": True} == client.get_feline() + def test_put_feline(client): result = client.put_feline({"meows": False, "hisses": True}) assert result == "Feline was correct!" + def test_get_cat(client): assert {"name": "Whiskers", "likesMilk": True, "meows": True, "hisses": True} == client.get_cat() + def test_put_cat(client): result = client.put_cat({"name": "Boots", "likesMilk": False, "meows": True, "hisses": False}) assert result == "Cat was correct!" + def test_get_kitten(client): - assert {"name": "Gatito", "likesMilk": True, "meows": True, "hisses": True, "eatsMiceYet": False} == client.get_kitten() + assert { + "name": "Gatito", + "likesMilk": True, + "meows": True, + "hisses": True, + "eatsMiceYet": False, + } == client.get_kitten() + def test_put_kitten(client): - result = client.put_kitten({"name": "Kitty", "likesMilk": False, "meows": True, "hisses": False, "eatsMiceYet": True}) + result = client.put_kitten( + {"name": "Kitty", "likesMilk": False, "meows": True, "hisses": False, "eatsMiceYet": True} + ) assert result == "Kitten was correct!" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_no_namespace_flag.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_no_namespace_flag.py index 347ad8c4dd2..8323b370b76 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_no_namespace_flag.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_no_namespace_flag.py @@ -26,11 +26,13 @@ import pytest from anything_client import AnythingClient + @pytest.fixture def client(): with AnythingClient() as client: yield client + def test_call(client): # make sure we can do a call with an sdk with no namespace flag - assert client.get_string() == 'anything' + assert client.get_string() == "anything" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_non_string_enums.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_non_string_enums.py index 3457337784e..e5aca34af4f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_non_string_enums.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_non_string_enums.py @@ -27,23 +27,28 @@ import pytest + @pytest.fixture def client(): with NonStringEnumsClient() as client: yield client + def test_put_int_enum(client): result = client.int_operations.put(200) assert result == "Nice job posting an int enum" + def test_get_int_enum(client): result = client.int_operations.get() assert result == 429 + def test_put_float_enum(client): result = client.float.put(200.4) assert result == "Nice job posting a float enum" + def test_get_float_enum(client): result = client.float.get() assert result == 429.1 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_number.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_number.py index 4cef8d44f62..e6414e09f67 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_number.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_number.py @@ -32,62 +32,77 @@ import pytest + @pytest.fixture def client(): with AutoRestNumberTestService() as client: yield client + def test_big_float(client): - client.number.put_big_float(3.402823e+20) - assert client.number.get_big_float() == 3.402823e+20 + client.number.put_big_float(3.402823e20) + assert client.number.get_big_float() == 3.402823e20 + def test_small_float(client): client.number.put_small_float(3.402823e-20) - assert client.number.get_small_float() == 3.402823e-20 + assert client.number.get_small_float() == 3.402823e-20 + def test_big_double(client): - client.number.put_big_double(2.5976931e+101) - assert client.number.get_big_double() == 2.5976931e+101 + client.number.put_big_double(2.5976931e101) + assert client.number.get_big_double() == 2.5976931e101 + def test_small_double(client): client.number.put_small_double(2.5976931e-101) - assert client.number.get_small_double() == 2.5976931e-101 + assert client.number.get_small_double() == 2.5976931e-101 + def test_big_double_negative_decimal(client): client.number.put_big_double_negative_decimal() - assert client.number.get_big_double_negative_decimal() == -99999999.99 + assert client.number.get_big_double_negative_decimal() == -99999999.99 + def test_big_double_positive_decimal(client): client.number.put_big_double_positive_decimal() - assert client.number.get_big_double_positive_decimal() == 99999999.99 + assert client.number.get_big_double_positive_decimal() == 99999999.99 + def test_big_decimal(client): - client.number.put_big_decimal(2.5976931e+101) - assert client.number.get_big_decimal() == 2.5976931e+101 + client.number.put_big_decimal(2.5976931e101) + assert client.number.get_big_decimal() == 2.5976931e101 + def test_small_decimal(client): client.number.put_small_decimal(2.5976931e-101) - assert client.number.get_small_decimal() == 2.5976931e-101 + assert client.number.get_small_decimal() == 2.5976931e-101 + def test_get_big_decimal_negative_decimal(client): client.number.put_big_decimal_positive_decimal() - assert client.number.get_big_decimal_negative_decimal() == -99999999.99 + assert client.number.get_big_decimal_negative_decimal() == -99999999.99 + def test_get_big_decimal_positive_decimal(client): client.number.put_big_decimal_negative_decimal() - assert client.number.get_big_decimal_positive_decimal() == 99999999.99 + assert client.number.get_big_decimal_positive_decimal() == 99999999.99 + def test_get_null(client): client.number.get_null() + def test_get_invalid_decimal(client): with pytest.raises(DecodeError): client.number.get_invalid_decimal() + def test_get_invalid_double(client): with pytest.raises(DecodeError): client.number.get_invalid_double() + def test_get_invalid_float(client): with pytest.raises(DecodeError): client.number.get_invalid_float() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_object_type.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_object_type.py index 1caca29fc2e..45b84090142 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_object_type.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_object_type.py @@ -29,20 +29,24 @@ import pytest + @pytest.fixture def client(): with ObjectTypeClient() as client: yield client + def test_get_object(client): response = client.get() assert response == {"message": "An object was successfully returned"} + def test_put_object_success(client): response = client.put({"foo": "bar"}) assert response is None + def test_put_object_fail(client): with pytest.raises(HttpResponseError) as ex: client.put({"should": "fail"}) - assert ex.value.response.json() == {"message": "The object you passed was incorrect"} \ No newline at end of file + assert ex.value.response.json() == {"message": "The object you passed was incorrect"} diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_parameterized_endpoint.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_parameterized_endpoint.py index c65cc9dddb5..efda0aee352 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_parameterized_endpoint.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_parameterized_endpoint.py @@ -26,6 +26,7 @@ import pytest from parameterizedendpointversiontolerant import ParmaterizedEndpointClient + @pytest.fixture def client(): with ParmaterizedEndpointClient(endpoint="http://localhost:3000") as client: diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_python3_only.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_python3_only.py index 1cb4372a348..bba15920a63 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_python3_only.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_python3_only.py @@ -26,8 +26,10 @@ import sys import pytest + def test_operation_groups(): from bodycomplexversiontolerant.operations import ArrayOperations from bodycomplexversiontolerant.operations._operations import ArrayOperations as ArrayOperationsPy3 + assert ArrayOperations == ArrayOperationsPy3 ArrayOperationsPy3(None, config=None, serializer=None, deserializer=None) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_required_optional.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_required_optional.py index 835c3b542d9..e46b5e7d17c 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_required_optional.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_required_optional.py @@ -31,54 +31,65 @@ import pytest + @pytest.fixture def client_required(): with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - ) as client: + "required_path", + "required_query", + ) as client: client._config.required_global_path = "required_path" client._config.required_global_query = "required_query" yield client + @pytest.fixture def client(): with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - ) as client: + "required_path", + "required_query", + ) as client: client._config.required_global_path = None client._config.required_global_query = None yield client + # These clients have a required global path and query def test_put_optional(client_required): client_required.implicit.put_optional_query(query_parameter=None) client_required.implicit.put_optional_body(None) client_required.implicit.put_optional_header(query_parameter=None) + def test_get_optional_global_query(client_required): client_required.implicit.get_optional_global_query(cls=None) + def test_post_optional_integer(client_required): client_required.explicit.post_optional_integer_parameter(None) client_required.explicit.post_optional_integer_property({"value": None}) client_required.explicit.post_optional_integer_header(header_parameter=None) + def test_post_optional_string(client_required): client_required.explicit.post_optional_string_parameter(None) client_required.explicit.post_optional_string_property({"value": None}) - client_required.explicit.post_optional_string_header(body_parameter=None) # header param that's called bodyParameter. confusing, but c'est la vie + client_required.explicit.post_optional_string_header( + body_parameter=None + ) # header param that's called bodyParameter. confusing, but c'est la vie + def test_post_optional_class(client_required): client_required.explicit.post_optional_class_parameter(None) client_required.explicit.post_optional_class_property({"value": None}) + def test_post_optional_array(client_required): client_required.explicit.post_optional_array_parameter(None) client_required.explicit.post_optional_array_property({"value": None}) client_required.explicit.post_optional_array_header(header_parameter=None) + def test_implicit_get_required(client): with pytest.raises(ValueError): client.implicit.get_required_path(None) @@ -89,6 +100,7 @@ def test_implicit_get_required(client): with pytest.raises(ValueError): client.implicit.get_required_global_query() + def test_post_required_string(client): with pytest.raises(ValueError): client.explicit.post_required_string_header(header_parameter=None) @@ -101,6 +113,7 @@ def test_post_required_string(client): client.explicit.post_required_string_property(None) assert "Not Found" in str(ex.value) + def test_post_required_array(client): with pytest.raises(TypeError): client.explicit.post_required_array_header(header_parameter=None) @@ -113,6 +126,7 @@ def test_post_required_array(client): client.explicit.post_required_array_property({"value": None}) assert "Not Found" in str(ex.value) + def test_post_required_class(client): with pytest.raises(HttpResponseError) as ex: client.explicit.post_required_class_parameter(None) @@ -124,14 +138,17 @@ def test_post_required_class(client): assert "Not Found" in str(ex.value) + def test_explict_put_optional_binary_body(client): client.explicit.put_optional_binary_body() + def test_explict_put_required_binary_body(client): test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: client.explicit.put_required_binary_body(stream_data) + def test_implicit_put_optional_binary_body(client): client.implicit.put_optional_binary_body() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_reserved_words.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_reserved_words.py index 8fc5fd36544..b15a684cfe1 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_reserved_words.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_reserved_words.py @@ -26,31 +26,36 @@ import pytest from reservedwordsversiontolerant import ReservedWordsClient + @pytest.fixture def client(): with ReservedWordsClient() as client: yield client + def test_operation_group_import(client): client.import_operations.operation_one(parameter1="foo") + def test_operation_with_content_param(client): client.operation_with_content_param(b"hello, world") + def test_operation_with_json_param(client): client.operation_with_json_param({"hello": "world"}) + def test_operation_with_data_param(client): client.operation_with_data_param({"data": "hello", "world": "world"}) + def test_operation_with_files_param(client): - client.operation_with_files_param(files = { - "file_name": "my.txt", - "files": b'bytes' - }) + client.operation_with_files_param(files={"file_name": "my.txt", "files": b"bytes"}) + def test_operation_with_url(client): client.operation_with_url("foo", header_parameters="x-ms-header", query_parameters=["one", "two"]) + def test_operation_with_enum(client): client.reserved_enum(enum_parameter="import") diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_security.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_security.py index 46f859bb985..c0d94235ab3 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_security.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_security.py @@ -29,13 +29,15 @@ from azure.core.pipeline.policies import AzureKeyCredentialPolicy from azure.core.pipeline.policies import BearerTokenCredentialPolicy + def test_security_aad_swagger(credential): client = AutorestSecurityAad(credential=credential) assert isinstance(client._config.authentication_policy, BearerTokenCredentialPolicy) client.head(enforce_https=False) + def test_security_key_swagger(): # the key value shall keep same with https://github.com/Azure/autorest.testserver/tree/main/src/test-routes/security.ts - client = AutorestSecurityKey(credential=AzureKeyCredential('123456789')) + client = AutorestSecurityKey(credential=AzureKeyCredential("123456789")) assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) client.head() diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_send_request.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_send_request.py index 4504f398c75..8343a386e2f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_send_request.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_send_request.py @@ -32,45 +32,48 @@ cwd = dirname(realpath(__file__)) + def test_send_request_with_body_get_model_deserialize(): - from bodycomplexversiontolerant import AutoRestComplexTestService\ + from bodycomplexversiontolerant import AutoRestComplexTestService client = AutoRestComplexTestService() - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = client.send_request(request) response.raise_for_status() deserialized = response.json() - assert 2 == deserialized['id'] - assert "Siameeee" == deserialized['name'] - assert -1 == deserialized['hates'][1]['id'] - assert "Tomato" == deserialized['hates'][1]['name'] + assert 2 == deserialized["id"] + assert "Siameeee" == deserialized["name"] + assert -1 == deserialized["hates"][1]["id"] + assert "Tomato" == deserialized["hates"][1]["name"] + def test_send_request_with_stream_get_direct_json(): from bodycomplexversiontolerant import AutoRestComplexTestService client = AutoRestComplexTestService() - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, + request = HttpRequest( + "GET", + "/complex/inheritance/valid", + headers={"Accept": "application/json"}, ) response = client.send_request(request, stream=True) - data = b''.join([chunk for chunk in response.iter_bytes()]).decode('utf-8') + data = b"".join([chunk for chunk in response.iter_bytes()]).decode("utf-8") json_response = json.loads(data) - assert 2 == json_response['id'] - assert "Siameeee" == json_response['name'] - assert - 1 == json_response['hates'][1]['id'] - assert "Tomato" == json_response['hates'][1]['name'] + assert 2 == json_response["id"] + assert "Siameeee" == json_response["name"] + assert -1 == json_response["hates"][1]["id"] + assert "Tomato" == json_response["hates"][1]["name"] + def test_send_request_with_body_put_json_dumps(): from bodycomplexversiontolerant import AutoRestComplexTestService @@ -81,32 +84,21 @@ def test_send_request_with_body_put_json_dumps(): "id": 2, "name": "Siameeee", "color": "green", - "hates": - [ - { - "id": 1, - "name": "Potato", - "food": "tomato" - }, - { - "id": -1, - "name": "Tomato", - "food": "french fries" - } - ], - "breed": "persian" + "hates": [{"id": 1, "name": "Potato", "food": "tomato"}, {"id": -1, "name": "Tomato", "food": "french fries"}], + "breed": "persian", } - request = HttpRequest("PUT", "/complex/inheritance/valid", - headers={ - 'Content-Type': 'application/json' - }, + request = HttpRequest( + "PUT", + "/complex/inheritance/valid", + headers={"Content-Type": "application/json"}, json=siamese_body, ) response = client.send_request(request) assert response.status_code == 200 + def test_send_request_get_stream(): from bodyfileversiontolerant import AutoRestSwaggerBATFileService @@ -114,10 +106,10 @@ def test_send_request_get_stream(): file_length = 0 with io.BytesIO() as file_handle: - request = HttpRequest("GET", "/files/stream/nonempty", - headers={ - 'Accept': 'image/png, application/json' - }, + request = HttpRequest( + "GET", + "/files/stream/nonempty", + headers={"Accept": "image/png, application/json"}, ) response = client.send_request(request, stream=True) @@ -130,48 +122,61 @@ def test_send_request_get_stream(): file_length += len(data) file_handle.write(data) - assert file_length != 0 + assert file_length != 0 sample_file = realpath( - join(cwd, pardir, pardir, pardir, pardir, - "node_modules", "@microsoft.azure", "autorest.testserver", "routes", "sample.png")) + join( + cwd, + pardir, + pardir, + pardir, + pardir, + "node_modules", + "@microsoft.azure", + "autorest.testserver", + "routes", + "sample.png", + ) + ) - with open(sample_file, 'rb') as data: + with open(sample_file, "rb") as data: sample_data = hash(data.read()) assert sample_data == hash(file_handle.getvalue()) + def test_send_request_put_stream(): from bodyformdataversiontolerant import AutoRestSwaggerBATFormDataService client = AutoRestSwaggerBATFormDataService() test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') + test_bytes = bytearray(test_string, encoding="utf-8") with io.BytesIO(test_bytes) as stream_data: - request = HttpRequest("PUT", '/formdata/stream/uploadfile', - headers={ - 'Content-Type': 'application/octet-stream' - }, + request = HttpRequest( + "PUT", + "/formdata/stream/uploadfile", + headers={"Content-Type": "application/octet-stream"}, data=stream_data, ) response = client.send_request(request, stream=True) assert response.status_code == 200 + def test_send_request_full_url(): from bodycomplexversiontolerant import AutoRestComplexTestService client = AutoRestComplexTestService(endpoint="http://fakeUrl") - request = HttpRequest("GET", "http://localhost:3000/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, - ) + request = HttpRequest( + "GET", + "http://localhost:3000/complex/inheritance/valid", + headers={"Accept": "application/json"}, + ) response = client.send_request(request) response.raise_for_status() deserialized = response.json() - assert 2 == deserialized['id'] - assert "Siameeee" == deserialized['name'] - assert -1 == deserialized['hates'][1]['id'] - assert "Tomato" == deserialized['hates'][1]['name'] + assert 2 == deserialized["id"] + assert "Siameeee" == deserialized["name"] + assert -1 == deserialized["hates"][1]["id"] + assert "Tomato" == deserialized["hates"][1]["name"] diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_string_tests.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_string_tests.py index f6f5009dda7..9c93a7c34e3 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_string_tests.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_string_tests.py @@ -30,20 +30,24 @@ from .serializer import deserialize_base64, serialize_base64 import pytest + @pytest.fixture def client(): with AutoRestSwaggerBATService() as client: yield client + def test_null(client): assert client.string.get_null() is None client.string.put_null() + def test_empty(client): - assert "" == client.string.get_empty() + assert "" == client.string.get_empty() # changing this behavior because of this pr being merged: https://github.com/Azure/autorest.testserver/pull/145/files client.string.put_empty() + def test_mbcs(client): try: test_str = ( @@ -60,7 +64,8 @@ def test_mbcs(client): "\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" "\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" "\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + "\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") except AttributeError: test_str = ( @@ -77,43 +82,57 @@ def test_mbcs(client): b"\xb8\xb5\xef\xb9\x84\xef\xb8\xbb\xef\xb8\xb1\xef\xb8\xb3" b"\xef\xb8\xb4\xe2\x85\xb0\xe2\x85\xb9\xc9\x91\xee\x9f\x87" b"\xc9\xa1\xe3\x80\x87\xe3\x80\xbe\xe2\xbf\xbb\xe2\xba\x81" - b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac").decode('utf-8') + b"\xee\xa1\x83\xe4\x9c\xa3\xee\xa1\xa4\xe2\x82\xac" + ).decode("utf-8") assert test_str == client.string.get_mbcs() client.string.put_mbcs() + def test_whitespace(client): test_str = " Now is the time for all good men to come to the aid of their country " - assert test_str == client.string.get_whitespace() + assert test_str == client.string.get_whitespace() client.string.put_whitespace() + def test_get_not_provided(client): assert client.string.get_not_provided() is None + def test_enum_not_expandable(client): - assert 'red color' == client.enum.get_not_expandable() - client.enum.put_not_expandable('red color') + assert "red color" == client.enum.get_not_expandable() + client.enum.put_not_expandable("red color") # Autorest v3 is switching behavior here. Old Autorest would have thrown a serialization error, # but now we allow the user to pass strings as enums, so the raised exception is different. with pytest.raises(HttpResponseError): - client.enum.put_not_expandable('not a colour') + client.enum.put_not_expandable("not a colour") + def test_get_base64_encoded(client): - assert deserialize_base64(client.string.get_base64_encoded()) == 'a string that gets encoded with base64'.encode() + assert deserialize_base64(client.string.get_base64_encoded()) == "a string that gets encoded with base64".encode() + def test_base64_url_encoded(client): - assert deserialize_base64(client.string.get_base64_url_encoded()) == 'a string that gets encoded with base64url'.encode() - client.string.put_base64_url_encoded(serialize_base64('a string that gets encoded with base64url'.encode())) + assert ( + deserialize_base64(client.string.get_base64_url_encoded()) + == "a string that gets encoded with base64url".encode() + ) + client.string.put_base64_url_encoded(serialize_base64("a string that gets encoded with base64url".encode())) + def test_get_null_base64_url_encoded(client): assert client.string.get_null_base64_url_encoded() is None + def test_enum_referenced(client): - client.enum.put_referenced('red color') + client.enum.put_referenced("red color") + + assert client.enum.get_referenced() == "red color" - assert client.enum.get_referenced() == 'red color' def test_enum_referenced_constant(client): client.enum.put_referenced_constant({"ColorConstant": "green-color"}) - assert client.enum.get_referenced_constant() == {'field1': 'Sample String'} # there's no constant on the response, so just getting field1 + assert client.enum.get_referenced_constant() == { + "field1": "Sample String" + } # there's no constant on the response, so just getting field1 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_time.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_time.py index 5d2e6997af3..74b79becd85 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_time.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_time.py @@ -31,14 +31,17 @@ import pytest from .serializer import serialize_time, deserialize_time + @pytest.fixture def client(): with AutoRestTimeTestService() as client: yield client + def test_get(client): assert deserialize_time(client.time.get()) == datetime.time(11, 34, 56) + def test_put(client): result = client.time.put(serialize_time(datetime.time(8, 7, 56))) assert result == "Nice job posting time" diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_tracing.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_tracing.py index a49b5d6f0b9..03faca6596d 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_tracing.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_tracing.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -33,6 +32,7 @@ def has_tracing_decorator(function): source = inspect.getsource(function) return "def wrapper_use_tracer" in source or "@distributed_trace" in source + def test_url(): - with AutoRestUrlTestService('', endpoint="dummy url") as client: - assert has_tracing_decorator(client.paths.get_boolean_false) \ No newline at end of file + with AutoRestUrlTestService("", endpoint="dummy url") as client: + assert has_tracing_decorator(client.paths.get_boolean_false) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_url.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_url.py index 69ec8007694..6e6652faf5f 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_url.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_url.py @@ -30,164 +30,203 @@ import pytest + @pytest.fixture def client(): - with AutoRestUrlTestService('') as client: + with AutoRestUrlTestService("") as client: yield client + @pytest.fixture def multi_client(): with AutoRestUrlMutliCollectionFormatTestService() as client: yield client + @pytest.fixture def test_array_query(): return ["ArrayQuery1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + def test_byte_empty_and_null(client): client.paths.byte_empty() with pytest.raises(ValueError): client.paths.byte_null(None) + def test_byte_multi_byte(client): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") client.paths.byte_multi_byte(u_bytes) + def test_date_null(client): with pytest.raises(ValueError): client.paths.date_null(None) + def test_date_time_null(client): with pytest.raises(ValueError): client.paths.date_time_null(None) + def test_date_time_valid(client): client.paths.date_time_valid() + def test_date_valid(client): client.paths.date_valid() + def test_unix_time_url(client): client.paths.unix_time_url(datetime(year=2016, month=4, day=13)) + def test_double_decimal(client): client.paths.double_decimal_negative() client.paths.double_decimal_positive() + def test_float_scientific(client): client.paths.float_scientific_negative() client.paths.float_scientific_positive() + def test_get_boolean(client): client.paths.get_boolean_false() client.paths.get_boolean_true() + def test_int(client): client.paths.get_int_negative_one_million() client.paths.get_int_one_million() + def test_get_long(client): client.paths.get_negative_ten_billion() client.paths.get_ten_billion() + def test_string_empty_and_null(client): client.paths.string_empty() with pytest.raises(ValueError): client.paths.string_null(None) + def test_array_csv_in_path(client): test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] client.paths.array_csv_in_path(test_array) + def test_string_url_encoded(client): client.paths.string_url_encoded() + def test_paths_unicode(client): client.paths.string_unicode() + def test_string_url_non_encoded(client): client.paths.string_url_non_encoded() + def test_enum_valid(client): client.paths.enum_valid("green color") + def test_enum_null(client): with pytest.raises(ValueError): client.paths.enum_null(None) + def test_base64_url(client): client.paths.base64_url("lorem".encode()) + def test_queries_byte(client): client.queries.byte_empty() - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') + u_bytes = bytearray("\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding="utf-8") client.queries.byte_multi_byte(byte_query=u_bytes) client.queries.byte_null() + def test_queries_date(client): client.queries.date_null() client.queries.date_valid() + def test_queries_date_time(client): client.queries.date_time_null() client.queries.date_time_valid() + def test_queries_double(client): client.queries.double_null() client.queries.double_decimal_negative() client.queries.double_decimal_positive() + def test_queries_float_scientific(client): client.queries.float_scientific_negative() client.queries.float_scientific_positive() client.queries.float_null() + def test_queries_boolean(client): client.queries.get_boolean_false() client.queries.get_boolean_true() client.queries.get_boolean_null() + def test_queries_int(client): client.queries.get_int_negative_one_million() client.queries.get_int_one_million() client.queries.get_int_null() + def test_queries_long(client): client.queries.get_negative_ten_billion() client.queries.get_ten_billion() client.queries.get_long_null() + def test_queries_string(client): client.queries.string_empty() client.queries.string_null() client.queries.string_url_encoded() + def test_queries_enum(client): client.queries.enum_valid(enum_query="green color") client.queries.enum_null(enum_query=None) + def test_queries_unicode(client): client.queries.string_unicode() + def test_array_string_csv(client, test_array_query): client.queries.array_string_csv_empty(array_query=[]) client.queries.array_string_csv_null(array_query=None) client.queries.array_string_csv_valid(array_query=test_array_query) + def test_array_string_miscellaneous(client, test_array_query): client.queries.array_string_pipes_valid(array_query=test_array_query) client.queries.array_string_ssv_valid(array_query=test_array_query) client.queries.array_string_tsv_valid(array_query=test_array_query) + def test_array_string_multi(multi_client, test_array_query): multi_client.queries.array_string_multi_empty(array_query=[]) multi_client.queries.array_string_multi_null() multi_client.queries.array_string_multi_valid(array_query=test_array_query) + def test_array_string_no_collection_format(client): - client.queries.array_string_no_collection_format_empty(array_query=['hello', 'nihao', 'bonjour']) + client.queries.array_string_no_collection_format_empty(array_query=["hello", "nihao", "bonjour"]) + def test_get_all_with_values(client): client._config.global_string_path = "globalStringPath" @@ -199,6 +238,7 @@ def test_get_all_with_values(client): local_string_query="localStringQuery", ) + def test_get_global_and_local_query_null(client): client._config.global_string_path = "globalStringPath" client.path_items.get_global_and_local_query_null( @@ -208,6 +248,7 @@ def test_get_global_and_local_query_null(client): local_string_query=None, ) + def test_get_global_query_null(client): client._config.global_string_path = "globalStringPath" client.path_items.get_global_query_null( @@ -217,6 +258,7 @@ def test_get_global_query_null(client): local_string_query="localStringQuery", ) + def test_get_local_path_item_query_null(client): client._config.global_string_path = "globalStringPath" client._config.global_string_query = "globalStringQuery" @@ -227,9 +269,12 @@ def test_get_local_path_item_query_null(client): local_string_query=None, ) + def test_operation_groups(): from urlversiontolerant.operations import QueriesOperations - from urlmulticollectionformatversiontolerant.operations import QueriesOperations as MultiCollectionFormatQueriesOperations + from urlmulticollectionformatversiontolerant.operations import ( + QueriesOperations as MultiCollectionFormatQueriesOperations, + ) with pytest.raises(ImportError): from urlversiontolerant.operations import _operations_py3 @@ -238,7 +283,9 @@ def test_operation_groups(): from urlmulticollectionformatversiontolerant.operations import _operations_py3 from urlversiontolerant.operations._operations import QueriesOperations as QueriesOperationsPy2 + assert QueriesOperations == QueriesOperationsPy2 from urlmulticollectionformatversiontolerant.operations._operations import QueriesOperations as QueriesOperationsPy2 - assert MultiCollectionFormatQueriesOperations == QueriesOperationsPy2 \ No newline at end of file + + assert MultiCollectionFormatQueriesOperations == QueriesOperationsPy2 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_urlencoded.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_urlencoded.py index 9cc7e7340be..c30d8756f70 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_urlencoded.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_urlencoded.py @@ -27,11 +27,13 @@ import pytest from bodyformurlencodeddataversiontolerant import BodyFormsDataURLEncoded + @pytest.fixture def client(): with BodyFormsDataURLEncoded() as client: yield client + def test_update_pet_with_form(client): client.formdataurlencoded.update_pet_with_form( 1, @@ -40,12 +42,11 @@ def test_update_pet_with_form(client): "pet_food": "meat", "pet_age": 42, "name": "Fido", - } + }, ) + def test_partial_constant_body(client): - client.formdataurlencoded.partial_constant_body({ - "access_token": "foo", - "grant_type": "access_token", - "service": "bar" - }) + client.formdataurlencoded.partial_constant_body( + {"access_token": "foo", "grant_type": "access_token", "service": "bar"} + ) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_validation.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_validation.py index c16e31e8b88..eb3bef8052e 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_validation.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_validation.py @@ -29,12 +29,14 @@ import pytest + @pytest.fixture def client(): with AutoRestValidationTest("abc123") as client: client.api_version = "12-34-5678" yield client + @pytest.fixture def constant_body(): """This is NOT considering the constant body, this should work with @@ -42,46 +44,46 @@ def constant_body(): See https://github.com/Azure/autorest.modelerfour/issues/83 """ return { - 'child': { - 'constProperty': 'constant' - }, - 'constChild': { - 'constProperty': 'constant', - 'constProperty2': 'constant2' - }, - 'constInt': 0, - 'constString': 'constant', - 'constStringAsEnum': 'constant_string_as_enum' + "child": {"constProperty": "constant"}, + "constChild": {"constProperty": "constant", "constProperty2": "constant2"}, + "constInt": 0, + "constString": "constant", + "constStringAsEnum": "constant_string_as_enum", } def test_with_constant_in_path(client): client.get_with_constant_in_path() + def test_post_with_constant_in_body(client, constant_body): product = client.post_with_constant_in_body(body=constant_body) assert product is not None -# Note: the client-side-validation is not supported for low-level client, + +# Note: the client-side-validation is not supported for low-level client, # so this request with faked path will be sent to testserver and get an ResourceNotFoundError def test_fakedpath_validation(client): with pytest.raises(ResourceNotFoundError) as ex: client.validation_of_method_parameters("1", 100) + @pytest.mark.skip(reason="Not generating models yet, can't validate") def test_minimum_ex_validation(client, constant_body): with pytest.raises(ValueError) as ex: - constant_body['capacity'] = 0 + constant_body["capacity"] = 0 client.validation_of_body("123", 150, constant_body) + @pytest.mark.skip(reason="Not generating models yet, can't validate") def test_maximum_ex_validation(client, constant_body): with pytest.raises(ValueError) as ex: - constant_body['capacity'] = 100 + constant_body["capacity"] = 100 client.validation_of_body("123", 150, constant_body) + @pytest.mark.skip(reason="Not generating models yet, can't validate") def test_max_items_validation(client, constant_body): with pytest.raises(ValueError) as ex: - constant_body.display_names = ["item1","item2","item3","item4","item5","item6","item7"] + constant_body.display_names = ["item1", "item2", "item3", "item4", "item5", "item6", "item7"] client.validation_of_body("123", 150, constant_body) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xml.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xml.py index 00bd1bebe83..0d11369af6a 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xml.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xml.py @@ -41,6 +41,7 @@ def client(): def _assert_with_log(func, *args, **kwargs): def raise_for_status(response, deserialized, headers): response.http_response._internal_response.raise_for_status() + try: http_response = func(*args, cls=raise_for_status, **kwargs) except Exception as err: @@ -75,7 +76,7 @@ def test_simple(client): assert slide2.title == "Overview" assert len(slide2.items) == 3 assert slide2.items[0] == "Why WonderWidgets are great" - assert slide2.items[1] == '' + assert slide2.items[1] == "" assert slide2.items[2] == "Who buys WonderWidgets" _assert_with_log(client.xml.put_simple, slideshow) @@ -84,7 +85,7 @@ def test_simple(client): def test_empty_child_element(client): banana = client.xml.get_empty_child_element() # That's the point of this test, it was an empty node. - assert banana.flavor == '' + assert banana.flavor == "" _assert_with_log(client.xml.put_empty_child_element, banana) @@ -121,8 +122,8 @@ def test_get_empty(client): def test_wrapped_lists(client): bananas = client.xml.get_wrapped_lists() - assert bananas.good_apples == ['Fuji', 'Gala'] - assert bananas.bad_apples == ['Red Delicious'] + assert bananas.good_apples == ["Fuji", "Gala"] + assert bananas.bad_apples == ["Red Delicious"] _assert_with_log(client.xml.put_wrapped_lists, bananas) @@ -153,9 +154,9 @@ def test_list_blobs(client): assert blob.properties.content_length == 100 assert blob.properties.content_type == "text/html" # Check that an empty field in the XML is empty string - assert blob.properties.content_encoding == '' + assert blob.properties.content_encoding == "" assert blob.properties.content_language == "en-US" - assert blob.properties.content_md5 == '' + assert blob.properties.content_md5 == "" assert blob.properties.cache_control == "no-cache" assert blob.properties.blob_type == BlobType.block_blob # Check that a field NOT in the XML is None @@ -176,7 +177,7 @@ def test_service_properties(client): def test_acls(client): acls = client.xml.get_acls() assert len(acls) == 1 - assert acls[0].id == 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' + assert acls[0].id == "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=" _assert_with_log(client.xml.put_acls, acls) @@ -196,5 +197,5 @@ def test_bytes(client): def test_url(client): url_object = client.xml.get_uri() assert isinstance(url_object, ModelWithUrlProperty) - assert url_object.url == 'https://myaccount.blob.core.windows.net/' + assert url_object.url == "https://myaccount.blob.core.windows.net/" client.xml.put_uri(url_object) diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xms_error.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xms_error.py index e3194859753..2c072d06c65 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xms_error.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_xms_error.py @@ -31,17 +31,19 @@ from xmserrorresponseversiontolerant import XMSErrorResponseExtensions + @pytest.fixture def client(): with XMSErrorResponseExtensions(endpoint="http://localhost:3000") as client: yield client + def test_get_by_pet_id_success(client): pet = client.pet.get_pet_by_id("tommy") - assert pet['name'] == "Tommy Tomson" + assert pet["name"] == "Tommy Tomson" - client.pet.get_pet_by_id('django') # no fail, 202 + client.pet.get_pet_by_id("django") # no fail, 202 def test_get_by_pet_id_discriminator(client): @@ -49,14 +51,15 @@ def test_get_by_pet_id_discriminator(client): with pytest.raises(HttpResponseError) as excinfo: client.pet.get_pet_by_id("coyoteUgly") - assert excinfo.value.response.json()['whatNotFound'] == 'AnimalNotFound' - assert excinfo.value.response.json()['reason'] == "the type of animal requested is not available" + assert excinfo.value.response.json()["whatNotFound"] == "AnimalNotFound" + assert excinfo.value.response.json()["reason"] == "the type of animal requested is not available" with pytest.raises(HttpResponseError) as excinfo: client.pet.get_pet_by_id("weirdAlYankovic") - assert excinfo.value.response.json()['whatNotFound'] == 'InvalidResourceLink' - assert excinfo.value.response.json()['reason'] == "link to pet not found" + assert excinfo.value.response.json()["whatNotFound"] == "InvalidResourceLink" + assert excinfo.value.response.json()["reason"] == "link to pet not found" + def test_get_by_pet_id_basic_types(client): @@ -70,23 +73,26 @@ def test_get_by_pet_id_basic_types(client): assert excinfo.value.model is None # no model attached assert json.loads(excinfo.value.response.text()) == 123 + def test_do_something_success(client): result = client.pet.do_something("stay") with pytest.raises(KeyError): - result['actionResponse'] + result["actionResponse"] + def test_do_something_error(client): with pytest.raises(HttpResponseError) as excinfo: client.pet.do_something("jump") - assert excinfo.value.response.json()['errorType'] == 'PetSadError' - assert excinfo.value.response.json()['reason'] == "need more treats" + assert excinfo.value.response.json()["errorType"] == "PetSadError" + assert excinfo.value.response.json()["reason"] == "need more treats" with pytest.raises(ResourceNotFoundError) as excinfo: client.pet.do_something("fetch") + def test_error_deserialization_with_param_name_models(client): with pytest.raises(HttpResponseError) as excinfo: client.pet.has_models_param() - assert excinfo.value.response.json()['errorType'] == 'PetSadError' + assert excinfo.value.response.json()["errorType"] == "PetSadError" assert excinfo.value.status_code == 500 diff --git a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_zzz.py b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_zzz.py index 18f390f43a2..2b7fb4ec510 100644 --- a/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_zzz.py +++ b/packages/autorest.python/test/vanilla/version-tolerant/AcceptanceTests/test_zzz.py @@ -43,7 +43,7 @@ def test_ensure_coverage(self): # Please add missing features or failing tests here missing_features_or_bugs = { - 'ConstantsInBody': 1, # https://github.com/Azure/autorest.modelerfour/issues/83 + "ConstantsInBody": 1, # https://github.com/Azure/autorest.modelerfour/issues/83 "ResponsesScenarioF400DefaultModel": 1, "ResponsesScenarioF400DefaultNone": 1, } @@ -52,15 +52,16 @@ def test_ensure_coverage(self): self._print_report(report, not_supported, missing_features_or_bugs) missing_features_or_bugs = { - "putDateTimeMaxLocalNegativeOffset": 1, # Python doesn't support year 1000 - "putDateTimeMinLocalPositiveOffset": 1, # Python doesn't support BC time - 'putDateTimeMaxUtc7MS': 1, # Python doesn't support 7 digits ms datetime - 'FormdataStreamUploadFile': 1, # Form data not supported yet - 'StreamUploadFile': 1, # Form data not supported yet + "putDateTimeMaxLocalNegativeOffset": 1, # Python doesn't support year 1000 + "putDateTimeMinLocalPositiveOffset": 1, # Python doesn't support BC time + "putDateTimeMaxUtc7MS": 1, # Python doesn't support 7 digits ms datetime + "FormdataStreamUploadFile": 1, # Form data not supported yet + "StreamUploadFile": 1, # Form data not supported yet } for name in optional_report: if "Options" in name: - missing_features_or_bugs[name] = 1; # https://github.com/Azure/azure-sdk-for-python/pull/9322 + missing_features_or_bugs[name] = 1 + # https://github.com/Azure/azure-sdk-for-python/pull/9322 if "Multiapi" in name: # multiapi is in a separate test folder missing_features_or_bugs[name] = 1 @@ -70,7 +71,6 @@ def test_ensure_coverage(self): print("Optional coverage:") self._print_report(optional_report, not_supported, missing_features_or_bugs, fail_if_missing=False) - def _print_report(self, report, not_supported=None, missing_features_or_bugs=None, fail_if_missing=True): if not_supported: report.update(not_supported) @@ -87,7 +87,7 @@ def _print_report(self, report, not_supported=None, missing_features_or_bugs=Non print("FAILED TO EXECUTE {0}".format(s)) total_tests = len(report) - warnings.warn ("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) + warnings.warn("The test coverage is {0}/{1}.".format(total_tests - len(failed), total_tests)) if fail_if_missing: assert 0 == len(failed) diff --git a/packages/autorest.python/venvtools.py b/packages/autorest.python/venvtools.py index adea787012e..01e1300b1c8 100644 --- a/packages/autorest.python/venvtools.py +++ b/packages/autorest.python/venvtools.py @@ -31,15 +31,22 @@ def ensure_directories(self, env_dir): return self.context -def create(env_dir, system_site_packages=False, clear=False, - symlinks=False, with_pip=False, prompt=None, upgrade_deps=False): +def create( + env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None, upgrade_deps=False +): """Create a virtual environment in a directory.""" - builder = ExtendedEnvBuilder(system_site_packages=system_site_packages, - clear=clear, symlinks=symlinks, with_pip=with_pip, - prompt=prompt, upgrade_deps=upgrade_deps) + builder = ExtendedEnvBuilder( + system_site_packages=system_site_packages, + clear=clear, + symlinks=symlinks, + with_pip=with_pip, + prompt=prompt, + upgrade_deps=upgrade_deps, + ) builder.create(env_dir) return builder.context + @contextmanager def create_venv_with_package(packages): """Create a venv with these packages in a temp dir and yielf the env. @@ -54,17 +61,15 @@ def create_venv_with_package(packages): "pip", "install", ] - subprocess.check_call(pip_call + ['-U', 'pip']) + subprocess.check_call(pip_call + ["-U", "pip"]) if packages: subprocess.check_call(pip_call + packages) yield myenv + def python_run(venv_context, module, command=None, *, additional_dir="."): try: - cmd_line= [ - venv_context.env_exe, - "-m", module - ] + (command if command else []) + cmd_line = [venv_context.env_exe, "-m", module] + (command if command else []) print("Executing: {}".format(" ".join(cmd_line))) subprocess.run( cmd_line, diff --git a/packages/typespec-python/tasks.py b/packages/typespec-python/tasks.py index 266e8ff7238..2edfbca8398 100644 --- a/packages/typespec-python/tasks.py +++ b/packages/typespec-python/tasks.py @@ -135,9 +135,7 @@ def _default_package_name(spec: Path, category: Literal["azure", "unbranded"]) - return _package_name_folder(spec, category).replace("/", "-") -def _get_emitter_option( - spec: Path, category: Literal["azure", "unbranded"] -) -> List[Dict[str, str]]: +def _get_emitter_option(spec: Path, category: Literal["azure", "unbranded"]) -> List[Dict[str, str]]: name = _package_name_folder(spec, category) result = EMITTER_OPTIONS.get(name, []) if isinstance(result, dict): @@ -155,16 +153,10 @@ def _add_options( result = [] for config in _get_emitter_option(spec, category): config_copy = copy.copy(config) - config_copy[ - "emitter-output-dir" - ] = f"{generated_foder}/{config['package-name']}" + config_copy["emitter-output-dir"] = f"{generated_foder}/{config['package-name']}" result.append(config_copy) if not result: - result.append( - { - "emitter-output-dir": f"{generated_foder}/{_default_package_name(spec, category)}" - } - ) + result.append({"emitter-output-dir": f"{generated_foder}/{_default_package_name(spec, category)}"}) emitter_configs = [] for options in result: emitter_option = "" @@ -180,18 +172,14 @@ def _add_options( def _entry_file_name(path: Path) -> Path: if path.is_file(): return path - return ( - (path / "client.tsp") if (path / "client.tsp").exists() else (path / "main.tsp") - ) + return (path / "client.tsp") if (path / "client.tsp").exists() else (path / "main.tsp") + def _get_specification_dirs(category: Literal["azure", "unbranded"]) -> List[Path]: # we should remove the need for this by removing our local definition of mgmt sphere local_specification_folder = Path(f"test/{category}/specification") - return ( - [CADL_RANCH_DIR, local_specification_folder] - if local_specification_folder.exists() - else [CADL_RANCH_DIR] - ) + return [CADL_RANCH_DIR, local_specification_folder] if local_specification_folder.exists() else [CADL_RANCH_DIR] + def _all_specification_folders(category: Literal["azure", "unbranded"], filename: str = "main.tsp") -> List[Path]: @@ -202,6 +190,7 @@ def _all_specification_folders(category: Literal["azure", "unbranded"], filename if s.is_dir() and any(f for f in s.iterdir() if f.name == filename) ] + def _regenerate( c, specs: List[Path], @@ -214,9 +203,7 @@ def _regenerate( if name: specs = [s for s in specs if name.lower() in str(s)] if not name or name in "resiliency/srv-driven": - specs.extend( - s / "old.tsp" for s in _all_specification_folders(category, filename="old.tsp") - ) + specs.extend(s / "old.tsp" for s in _all_specification_folders(category, filename="old.tsp")) for spec in specs: for package_name in _get_package_names(spec, category): (generated_folder / package_name).mkdir(parents=True, exist_ok=True) @@ -224,9 +211,7 @@ def _regenerate( [ f"tsp compile {_entry_file_name(spec)} --emit={PLUGIN_DIR} {option}" for spec in specs - for option in _add_options( - spec, category, generated_folder, special_flags, debug - ) + for option in _add_options(spec, category, generated_folder, special_flags, debug) ] ) @@ -239,11 +224,7 @@ def is_invalid_folder(s: Path, invalid_folders: List[str] = []) -> bool: @task def regenerate_azure(c, name=None, debug=False): - specs = [ - s - for s in _all_specification_folders("azure") - if not is_invalid_folder(s) - ] + specs = [s for s in _all_specification_folders("azure") if not is_invalid_folder(s)] special_flags = {"flavor": "azure", "generate-test": "true"} _regenerate( c, @@ -255,8 +236,6 @@ def regenerate_azure(c, name=None, debug=False): ) - - @task def regenerate_unbranded(c, name=None, debug=False): specs = [ @@ -281,7 +260,7 @@ def regenerate( name=None, debug=False, flavor: Optional[Literal["azure", "unbranded"]] = None, -): +): if flavor == "azure": return regenerate_azure(c, name, debug) if flavor == "unbranded": @@ -289,11 +268,9 @@ def regenerate( regenerate_azure(c, name, debug) regenerate_unbranded(c, name, debug) + def _get_package_names(spec: Path, category: Literal["azure", "unbranded"]) -> List[str]: - result = [ - config["package-name"] - for config in _get_emitter_option(spec, category) - ] + result = [config["package-name"] for config in _get_emitter_option(spec, category)] if not result: result.append(_default_package_name(spec, category)) return result @@ -315,10 +292,7 @@ def _run_single_tsp(cmd): if result.ok: print(Fore.GREEN + f'Call "{cmd}" done with success') return True - print( - Fore.RED - + f'Call "{cmd}" failed with {result.return_code}\n{result.stdout}\n{result.stderr}' - ) + print(Fore.RED + f'Call "{cmd}" failed with {result.return_code}\n{result.stdout}\n{result.stderr}') output_folder = re.findall(r"emitter-output-dir=([^\s]+)", cmd)[0] shutil.rmtree(output_folder, ignore_errors=True) return False diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000000..e135e49b5f2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,18 @@ +[tool.black] +exclude = ''' +/( + \.git + | \.hg + | \.mypy_cache + | \.tox + | .*venv.* + | _build + | buck-out + | build + | dist + | node_modules + | Expected/AcceptanceTests + | generated/ +)/ +''' +line-length = 120